how to delete a particular file in Jenkins workspace via Jenkins groovy script2019 Community Moderator ElectionHow to restart Jenkins manually?Get absolute path to workspace directory in Jenkins Pipeline pluginJenkins Multipipeline Project with Groovy Pipeline ScriptAccessing Groovy class variables via Jenkins Declarative PipelineCreate new Jenkins jobs using Pipeline Job and Groovy scriptCreate a file with some content using Groovy in Jenkins pipelineGroovy shell script with a sed command in a Jenkins PipelineJenkins Multibranch Pipeline fails because it runs in Groovy SandboxHow to create jenkins pipeline job that will use jenkins file present in github, using groovy script placed inside init.groovy.d directoryExecute groovy script in a jenkins job

Is it a Cyclops number? "Nobody" knows!

Practical reasons to have both a large police force and bounty hunting network?

Problems with rounding giving too many digits

Where do you go through passport control when transiting through another Schengen airport on your way out of the Schengen area?

PTiJ: How should animals pray?

Why are special aircraft used for the carriers in the United States Navy?

Affine transformation of circular arc in 3D

When to use the term transposed instead of modulation?

Was it really inappropriate to write a pull request for the company I interviewed with?

Gemara word for QED

How do we objectively assess if a dialogue sounds unnatural or cringy?

Does the US political system, in principle, allow for a no-party system?

Why would the IRS ask for birth certificates or even audit a small tax return?

What is "desert glass" and what does it do to the PCs?

What is Tony Stark injecting into himself in Iron Man 3?

Should I use HTTPS on a domain that will only be used for redirection?

Why aren't there more gauls like Obelix?

What does it mean when I add a new variable to my linear model and the R^2 stays the same?

Giving a talk in my old university, how prominently should I tell students my salary?

Why won't the strings command stop?

Should we avoid writing fiction about historical events without extensive research?

Why doesn't "adolescent" take any articles in "listen to adolescent agonising"?

How can I be pwned if I'm not registered on the compromised site?

How to write a chaotic neutral protagonist and prevent my readers from thinking they are evil?



how to delete a particular file in Jenkins workspace via Jenkins groovy script



2019 Community Moderator ElectionHow to restart Jenkins manually?Get absolute path to workspace directory in Jenkins Pipeline pluginJenkins Multipipeline Project with Groovy Pipeline ScriptAccessing Groovy class variables via Jenkins Declarative PipelineCreate new Jenkins jobs using Pipeline Job and Groovy scriptCreate a file with some content using Groovy in Jenkins pipelineGroovy shell script with a sed command in a Jenkins PipelineJenkins Multibranch Pipeline fails because it runs in Groovy SandboxHow to create jenkins pipeline job that will use jenkins file present in github, using groovy script placed inside init.groovy.d directoryExecute groovy script in a jenkins job










0















i have a Jenkins pipeline, which triggers a Jenkins groovy script via SCM, this script will create a file(if the file is not present) and write else it will update the file and doing some stuffs, this file need to be deleted.



below is the code of creating, writing and updating the file.



node(node_label)
if (fileExists ( file_path+'/'+file_name ) )
def readContent = readFile file_path+'/'+file_name
writeFile file: file_path+'/'+file_name, text: readContent+'rn'+data
else
writeFile file: file_path+'/'+file_name, text:data




after doing some stuffs, i need to delete this file,
i tried deleting this as below, but its not working.



def Delfile = new File(path+'/'+file_name)
Delfile.delete()









share|improve this question
























  • Hi, check my answer, I am using the same, but only for all jobs which are being loaded, so it should works. So, what is not working in your case? You should to be able to print Delfile (due naming convention, camel-case, should be delFile btw.., its a groovy, "based" on java). so question is what are the values of path and file_name ,.. Did you getting any error, or whatever?

    – xxxvodnikxxx
    yesterday
















0















i have a Jenkins pipeline, which triggers a Jenkins groovy script via SCM, this script will create a file(if the file is not present) and write else it will update the file and doing some stuffs, this file need to be deleted.



below is the code of creating, writing and updating the file.



node(node_label)
if (fileExists ( file_path+'/'+file_name ) )
def readContent = readFile file_path+'/'+file_name
writeFile file: file_path+'/'+file_name, text: readContent+'rn'+data
else
writeFile file: file_path+'/'+file_name, text:data




after doing some stuffs, i need to delete this file,
i tried deleting this as below, but its not working.



def Delfile = new File(path+'/'+file_name)
Delfile.delete()









share|improve this question
























  • Hi, check my answer, I am using the same, but only for all jobs which are being loaded, so it should works. So, what is not working in your case? You should to be able to print Delfile (due naming convention, camel-case, should be delFile btw.., its a groovy, "based" on java). so question is what are the values of path and file_name ,.. Did you getting any error, or whatever?

    – xxxvodnikxxx
    yesterday














0












0








0








i have a Jenkins pipeline, which triggers a Jenkins groovy script via SCM, this script will create a file(if the file is not present) and write else it will update the file and doing some stuffs, this file need to be deleted.



below is the code of creating, writing and updating the file.



node(node_label)
if (fileExists ( file_path+'/'+file_name ) )
def readContent = readFile file_path+'/'+file_name
writeFile file: file_path+'/'+file_name, text: readContent+'rn'+data
else
writeFile file: file_path+'/'+file_name, text:data




after doing some stuffs, i need to delete this file,
i tried deleting this as below, but its not working.



def Delfile = new File(path+'/'+file_name)
Delfile.delete()









share|improve this question
















i have a Jenkins pipeline, which triggers a Jenkins groovy script via SCM, this script will create a file(if the file is not present) and write else it will update the file and doing some stuffs, this file need to be deleted.



below is the code of creating, writing and updating the file.



node(node_label)
if (fileExists ( file_path+'/'+file_name ) )
def readContent = readFile file_path+'/'+file_name
writeFile file: file_path+'/'+file_name, text: readContent+'rn'+data
else
writeFile file: file_path+'/'+file_name, text:data




after doing some stuffs, i need to delete this file,
i tried deleting this as below, but its not working.



def Delfile = new File(path+'/'+file_name)
Delfile.delete()






jenkins jenkins-pipeline jenkins-groovy






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited yesterday







Ann

















asked yesterday









AnnAnn

83




83












  • Hi, check my answer, I am using the same, but only for all jobs which are being loaded, so it should works. So, what is not working in your case? You should to be able to print Delfile (due naming convention, camel-case, should be delFile btw.., its a groovy, "based" on java). so question is what are the values of path and file_name ,.. Did you getting any error, or whatever?

    – xxxvodnikxxx
    yesterday


















  • Hi, check my answer, I am using the same, but only for all jobs which are being loaded, so it should works. So, what is not working in your case? You should to be able to print Delfile (due naming convention, camel-case, should be delFile btw.., its a groovy, "based" on java). so question is what are the values of path and file_name ,.. Did you getting any error, or whatever?

    – xxxvodnikxxx
    yesterday

















Hi, check my answer, I am using the same, but only for all jobs which are being loaded, so it should works. So, what is not working in your case? You should to be able to print Delfile (due naming convention, camel-case, should be delFile btw.., its a groovy, "based" on java). so question is what are the values of path and file_name ,.. Did you getting any error, or whatever?

– xxxvodnikxxx
yesterday






Hi, check my answer, I am using the same, but only for all jobs which are being loaded, so it should works. So, what is not working in your case? You should to be able to print Delfile (due naming convention, camel-case, should be delFile btw.., its a groovy, "based" on java). so question is what are the values of path and file_name ,.. Did you getting any error, or whatever?

– xxxvodnikxxx
yesterday













1 Answer
1






active

oldest

votes


















0














I have following for manual workspace cleanup, so as you mentioned it should work as well, check bellow.



I am assuming then you are probably not correctly getting file path



//load jobs
def jobs = Jenkins.instance.getAllItems(Job.class)

//iterate over
for(job in jobs)

//seems like they dont have workspace
if(job instanceof hudson.model.ExternalJob)
continue



String workspace = null

//pipelines dont have workspace
if(job instanceof org.jenkinsci.plugins.workflow.job.WorkflowJob)
println ("workflow job, not cleaning")
continue


try
workspace = job.workspace
catch(Exception e)
//already clean eg.
println ("no workspace, not cleaning")
workspace = null


if(workspace != null)
//creation of the workspace and modules folder
//again not sure, but sometimes was failing due boolean ..
if(workspace instanceof java.lang.Boolean)
println "cant cleanup"
continue


File folder = new File(workspace)

//Check if the Workspace folder really exists
if(folder!=null && folder.exists())
//workspace cleanup

//get files
File[] files = null
try
files=new File(workspace).listFiles().sort()
//println it.name

if(!it.isFile())
it.deleteDir()
else
it.delete()


catch(Exception e)
println "cant clean: " + workspace


else
println "workspace is not existing, not cleaning"





So, the core of the cleanup is:



 //get files
File[] files = null
try
files=new File(workspace).listFiles().sort()
//println it.name

if(!it.isFile())
it.deleteDir()
else
it.delete()


catch(Exception e)
println "cant clean: " + workspace






share|improve this answer






















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55022971%2fhow-to-delete-a-particular-file-in-jenkins-workspace-via-jenkins-groovy-script%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    I have following for manual workspace cleanup, so as you mentioned it should work as well, check bellow.



    I am assuming then you are probably not correctly getting file path



    //load jobs
    def jobs = Jenkins.instance.getAllItems(Job.class)

    //iterate over
    for(job in jobs)

    //seems like they dont have workspace
    if(job instanceof hudson.model.ExternalJob)
    continue



    String workspace = null

    //pipelines dont have workspace
    if(job instanceof org.jenkinsci.plugins.workflow.job.WorkflowJob)
    println ("workflow job, not cleaning")
    continue


    try
    workspace = job.workspace
    catch(Exception e)
    //already clean eg.
    println ("no workspace, not cleaning")
    workspace = null


    if(workspace != null)
    //creation of the workspace and modules folder
    //again not sure, but sometimes was failing due boolean ..
    if(workspace instanceof java.lang.Boolean)
    println "cant cleanup"
    continue


    File folder = new File(workspace)

    //Check if the Workspace folder really exists
    if(folder!=null && folder.exists())
    //workspace cleanup

    //get files
    File[] files = null
    try
    files=new File(workspace).listFiles().sort()
    //println it.name

    if(!it.isFile())
    it.deleteDir()
    else
    it.delete()


    catch(Exception e)
    println "cant clean: " + workspace


    else
    println "workspace is not existing, not cleaning"





    So, the core of the cleanup is:



     //get files
    File[] files = null
    try
    files=new File(workspace).listFiles().sort()
    //println it.name

    if(!it.isFile())
    it.deleteDir()
    else
    it.delete()


    catch(Exception e)
    println "cant clean: " + workspace






    share|improve this answer



























      0














      I have following for manual workspace cleanup, so as you mentioned it should work as well, check bellow.



      I am assuming then you are probably not correctly getting file path



      //load jobs
      def jobs = Jenkins.instance.getAllItems(Job.class)

      //iterate over
      for(job in jobs)

      //seems like they dont have workspace
      if(job instanceof hudson.model.ExternalJob)
      continue



      String workspace = null

      //pipelines dont have workspace
      if(job instanceof org.jenkinsci.plugins.workflow.job.WorkflowJob)
      println ("workflow job, not cleaning")
      continue


      try
      workspace = job.workspace
      catch(Exception e)
      //already clean eg.
      println ("no workspace, not cleaning")
      workspace = null


      if(workspace != null)
      //creation of the workspace and modules folder
      //again not sure, but sometimes was failing due boolean ..
      if(workspace instanceof java.lang.Boolean)
      println "cant cleanup"
      continue


      File folder = new File(workspace)

      //Check if the Workspace folder really exists
      if(folder!=null && folder.exists())
      //workspace cleanup

      //get files
      File[] files = null
      try
      files=new File(workspace).listFiles().sort()
      //println it.name

      if(!it.isFile())
      it.deleteDir()
      else
      it.delete()


      catch(Exception e)
      println "cant clean: " + workspace


      else
      println "workspace is not existing, not cleaning"





      So, the core of the cleanup is:



       //get files
      File[] files = null
      try
      files=new File(workspace).listFiles().sort()
      //println it.name

      if(!it.isFile())
      it.deleteDir()
      else
      it.delete()


      catch(Exception e)
      println "cant clean: " + workspace






      share|improve this answer

























        0












        0








        0







        I have following for manual workspace cleanup, so as you mentioned it should work as well, check bellow.



        I am assuming then you are probably not correctly getting file path



        //load jobs
        def jobs = Jenkins.instance.getAllItems(Job.class)

        //iterate over
        for(job in jobs)

        //seems like they dont have workspace
        if(job instanceof hudson.model.ExternalJob)
        continue



        String workspace = null

        //pipelines dont have workspace
        if(job instanceof org.jenkinsci.plugins.workflow.job.WorkflowJob)
        println ("workflow job, not cleaning")
        continue


        try
        workspace = job.workspace
        catch(Exception e)
        //already clean eg.
        println ("no workspace, not cleaning")
        workspace = null


        if(workspace != null)
        //creation of the workspace and modules folder
        //again not sure, but sometimes was failing due boolean ..
        if(workspace instanceof java.lang.Boolean)
        println "cant cleanup"
        continue


        File folder = new File(workspace)

        //Check if the Workspace folder really exists
        if(folder!=null && folder.exists())
        //workspace cleanup

        //get files
        File[] files = null
        try
        files=new File(workspace).listFiles().sort()
        //println it.name

        if(!it.isFile())
        it.deleteDir()
        else
        it.delete()


        catch(Exception e)
        println "cant clean: " + workspace


        else
        println "workspace is not existing, not cleaning"





        So, the core of the cleanup is:



         //get files
        File[] files = null
        try
        files=new File(workspace).listFiles().sort()
        //println it.name

        if(!it.isFile())
        it.deleteDir()
        else
        it.delete()


        catch(Exception e)
        println "cant clean: " + workspace






        share|improve this answer













        I have following for manual workspace cleanup, so as you mentioned it should work as well, check bellow.



        I am assuming then you are probably not correctly getting file path



        //load jobs
        def jobs = Jenkins.instance.getAllItems(Job.class)

        //iterate over
        for(job in jobs)

        //seems like they dont have workspace
        if(job instanceof hudson.model.ExternalJob)
        continue



        String workspace = null

        //pipelines dont have workspace
        if(job instanceof org.jenkinsci.plugins.workflow.job.WorkflowJob)
        println ("workflow job, not cleaning")
        continue


        try
        workspace = job.workspace
        catch(Exception e)
        //already clean eg.
        println ("no workspace, not cleaning")
        workspace = null


        if(workspace != null)
        //creation of the workspace and modules folder
        //again not sure, but sometimes was failing due boolean ..
        if(workspace instanceof java.lang.Boolean)
        println "cant cleanup"
        continue


        File folder = new File(workspace)

        //Check if the Workspace folder really exists
        if(folder!=null && folder.exists())
        //workspace cleanup

        //get files
        File[] files = null
        try
        files=new File(workspace).listFiles().sort()
        //println it.name

        if(!it.isFile())
        it.deleteDir()
        else
        it.delete()


        catch(Exception e)
        println "cant clean: " + workspace


        else
        println "workspace is not existing, not cleaning"





        So, the core of the cleanup is:



         //get files
        File[] files = null
        try
        files=new File(workspace).listFiles().sort()
        //println it.name

        if(!it.isFile())
        it.deleteDir()
        else
        it.delete()


        catch(Exception e)
        println "cant clean: " + workspace







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered yesterday









        xxxvodnikxxxxxxvodnikxxx

        92811027




        92811027





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55022971%2fhow-to-delete-a-particular-file-in-jenkins-workspace-via-jenkins-groovy-script%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Identity Server 4 is not redirecting to Angular app after login2019 Community Moderator ElectionIdentity Server 4 and dockerIdentityserver implicit flow unauthorized_clientIdentityServer Hybrid Flow - Access Token is null after user successful loginIdentity Server to MVC client : Page Redirect After loginLogin with Steam OpenId(oidc-client-js)Identity Server 4+.NET Core 2.0 + IdentityIdentityServer4 post-login redirect not working in Edge browserCall to IdentityServer4 generates System.NullReferenceException: Object reference not set to an instance of an objectIdentityServer4 without HTTPS not workingHow to get Authorization code from identity server without login form

            2005 Ahvaz unrest Contents Background Causes Casualties Aftermath See also References Navigation menue"At Least 10 Are Killed by Bombs in Iran""Iran"Archived"Arab-Iranians in Iran to make April 15 'Day of Fury'"State of Mind, State of Order: Reactions to Ethnic Unrest in the Islamic Republic of Iran.10.1111/j.1754-9469.2008.00028.x"Iran hangs Arab separatists"Iran Overview from ArchivedConstitution of the Islamic Republic of Iran"Tehran puzzled by forged 'riots' letter""Iran and its minorities: Down in the second class""Iran: Handling Of Ahvaz Unrest Could End With Televised Confessions""Bombings Rock Iran Ahead of Election""Five die in Iran ethnic clashes""Iran: Need for restraint as anniversary of unrest in Khuzestan approaches"Archived"Iranian Sunni protesters killed in clashes with security forces"Archived

            Can't initialize raids on a new ASUS Prime B360M-A motherboard2019 Community Moderator ElectionSimilar to RAID config yet more like mirroring solution?Can't get motherboard serial numberWhy does the BIOS entry point start with a WBINVD instruction?UEFI performance Asus Maximus V Extreme