jenkins执行shell文件_如何从Jenkinsfile(groovy)中获取使用执行的Shell命令的输出?...

If you want to get the stdout AND know whether the command succeeded or not, just use returnStdout and wrap it in an exception handler:

scripted pipeline

try {

// Fails with non-zero exit if dir1 does not exist

def dir1 = sh(script:'ls -la dir1', returnStdout:true).trim()

} catch (Exception ex) {

println("Unable to read dir1: ${ex}")

}

output:

[Pipeline] sh

[Test-Pipeline] Running shell script

+ ls -la dir1

ls: cannot access dir1: No such file or directory

[Pipeline] echo

unable to read dir1: hudson.AbortException: script returned exit code 2

Unfortunately hudson.AbortException is missing any useful method to obtain that exit status, so if the actual value is required you'd need to parse it out of the message (ugh!)

Contrary to the Javadoc https://javadoc.jenkins-ci.org/hudson/AbortException.html the build is not failed when this exception is caught. It fails when it's not caught!

Update:

If you also want the STDERR output from the shell command, there could be a couple of possible approaches:

a) Redirect STDERR to STDOUT 2>&1

- but it's then up to you to parse that out of the main output though, and you won't get the output if the command failed - because you're in the exception handler.

b) redirect STDERR to a temporary file (the name of which you prepare earlier) 2>filename (but remember to clean up the file afterwards) - ie. main code becomes:

def stderrfile = 'stderr.out'

try {

def dir1 = sh(script:"ls -la dir1 2>${stderrfile}", returnStdout:true).trim()

} catch (Exception ex) {

def errmsg = readFile(stderrfile)

println("Unable to read dir1: ${ex} - ${errmsg}")

}

c) Go the other way, set returnStatus=true instead, dispense with the exception handler and always capture output to a file, ie:

def outfile = 'stdout.out'

def status = sh(script:"ls -la dir1 >${outfile} 2>&1", returnStatus:true)

def output = readFile(outfile).trim()

if (status == 0) {

// output is directory listing from stdout

} else {

// output is error message from stderr

}

Caveat: the above code is Unix/Linux-specific - Windows requires completely different shell commands.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值