Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I execute shell script from Jenkins groovy script in the parameters option?

I want to call a shell script in the Uno-Choice Dynamic Reference Parameter and perform some operation (create some files and call some other shell scripts from the called shell script) .

As of now I am able to call shell script and cat some files but I am not able to create new files or call another shell script from within this.

def sout = new StringBuffer(), serr = new StringBuffer()

// 1) 
def proc ='cat /home/path/to/file'.execute()
//display contents of file

// 2) 
def proc="sh /home/path/to/shell/script.sh".execute()
//to call a shell script but the above dosent work if I echo some contents
//into some file.

proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(1000)
return sout.tokenize()

eg:- in script.sh if I add line

echo "hello world" > test

then test file is not created

for more understanding:

Groovy executing shell commands

http://jenkins-ci.361315.n4.nabble.com/Executing-a-shell-python-command-in-Jenkins-Dynamic-Choice-Parameter-Plugin-td4711174.html

like image 224
Triangle Avatar asked May 15 '15 07:05

Triangle


1 Answers

Since you are running the bash scripts from a groovy wrapper, the stdout and stderr are already redirected to the groovy wrapper. In order to override this, you need to use exec within a shell script.

for example:

the groovy script:

def sout = new StringBuffer(), serr = new StringBuffer()

def proc ='./script.sh'.execute()

proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(1000)
println sout

The shell script named script.sh and is located in the same folder:

#!/bin/bash
echo "Test redirect"

Running the groovy with the shell script above will produce the output Test redirect on the stdout of the groovy script

Now add stdout redirection with exec in the script.sh`:

#!/bin/bash
exec 1>/tmp/test
echo "Test redirect"

Now running the groovy script will create a file /tmp/test with a content Test redirect

You can read more about I/O redirection in bash here

like image 55
Yuri G. Avatar answered Sep 28 '22 08:09

Yuri G.