Fullmenu null

 

31 August 2017

It is very common that you have to execute repeatedly shell commands and depending on the its response perform actions, such as executing a command or another, etc. These commands can be a simple list of files (dir), copy files (` cp`, copy) or more elaborate ones.

Many times we must execute those commands repeatedly (once for each directory, for each file, etc) and even conditional (if the invocation of this command has gone well to perform these actions and if not these others).

For this we usually use batch files (.bat in Windows, .sh in Linux) where we can deal with problems discussed above.

In this environment, Groovy offers us the ability to execute commands with the help of the .execute () method of the String class and treat the output of this as if it were a chain, using all the language power.

Simple command

Suppose that in a * NIX system we would like to make a list of the files in a directory and show the output In uppercase. Our script would be:

String result = "ls -lt ".execute().text
println result.toUpperCase()

As we can see, we simply have to build a String with the command and call its method execute () This method returns an object that offers us the output of the command as a string through the property text that we can assign to a variable.

Wait for completion

If what we need is to launch a command and wait for it to finish to launch another command or another action again it can be done in the following way:

def resultado = new StringBuilder() //(1)
def error     = new StringBuilder()

def comando = "ls -lt".execute() //(2)
comando.consumeProcessOutput(resultado, error) //(3)
comando.waitForOrKill(1000) //(4)

if (!error.toString().equals("")) //(5)
    println "Error al ejecutar el comando"
else{
    println "Ejecutado correctamente"
    println resultado //(6)

}
  1. We define the variables where we will dump the result of our execute.

  2. We execute the command.

  3. We obtain the output of the command resulting from its execution.

  4. We set a time out to our command.

  5. In error case we will obtain the exit, in case our command fails and in case of correct functioning our value will be saved in result.

  6. The result is correct we can continue.


Script
def resultado = new StringBuilder() //(1)
def error     = new StringBuilder()

def comando = "ls -lt".execute() //(2)
comando.consumeProcessOutput(resultado, error) //(3)
comando.waitForOrKill(1000) //(4)

if (!error.toString().equals("")) //(5)
    println "Error al ejecutar el comando"
else{
    println "Ejecutado correctamente"
    println resultado //(6)

}