Forum Discussion

Apoorva6's avatar
Apoorva6
Frequent Contributor
9 years ago

Running Linux command via Groovy

HI,

 

I am trying to change directory via Groovy, but have this error back, please help me.

 

My Script as below:

 

if(actual.exists)
{

"cd /home/bgew".execute()
}
else
{
log.info("File not copied to ready folder")
}

 

I have below error:

 

01:41:02,279 ERROR [SoapUI] An error occurred [Cannot run program "cd": error=2, No such file or directory], see error log for details
java.io.IOException: Cannot run program "cd": error=2, No such file or directory
at java.lang.ProcessBuilder.start(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)

  • rupert_anderson's avatar
    rupert_anderson
    Valued Contributor

    Hi,

     

    Interestingly it seems Java (and therefore Groovy) has an issue with executing the "cd" command - hoave you seen this:

     

    http://stackoverflow.com/questions/4884681/how-to-use-cd-command-using-java-runtime

     

    I think the post explains to use absolute paths instead, and also goes on to show a work around.

     

    Maybe there's another way to do what you want with the allowed commands e.g. check file existance:

     

    def dir = new File( '/home/bgew' )
    
    if( dir.exists() ) {
     ...
    }

     

    Hope this helps,

    Rup

    • Apoorva6's avatar
      Apoorva6
      Frequent Contributor
      Hi Rup, Thanks for reply, I used both Runtime and Processbuilder, unfortunately I got same error. I just need to go to /home/bgew directory and run a script myScript.sh with an argument my argument .
      • rupert_anderson's avatar
        rupert_anderson
        Valued Contributor

        Hi,

         

        I made a simple script:

         

        #!/bin/bash
        
        echo "Hello World! $1 $2"

         

        Have you tried anything like:

         

        //method 1
        ['/Users/test/soapuiblog/hello.sh', 'arg1', 'arg2'].execute()
        
        //method 2
        def sout = new StringBuffer(), serr = new StringBuffer()
        //def proc = 'ls /temp'.execute()
        def proc = '/Users/test/soapuiblog/hello.sh arg1 arg2'.execute()
        proc.consumeProcessOutput(sout, serr)
        proc.waitForOrKill(1000)
        log.info "out> $sout err> $serr"

        Method 1 seems to execute without any error, but I couldn't be sure it had worked so I tried a way that captures the output method 2 (based on http://stackoverflow.com/questions/159148/groovy-executing-shell-commands) which also seemed to work giving the below log:

        Fri Apr 08 08:50:15 BST 2016:INFO:out> Hello World! arg1 arg2 err> 
        

        I ran this in a Groovy TestStep.

         

        Let me know if this works for you?

         

        Regards,

        Rup