在bash脚本输出中捕获退出代码以显示并登录 [英] catch exit code in bash script output to screen and log

查看:112
本文介绍了在bash脚本输出中捕获退出代码以显示并登录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图合并两条单独工作的线,但是我无法让它们一起工作.捕获并退出代码1:

I'm trying to combine 2 lines that work separately, but I can't get them to work together. To capture and exit code of 1:

Python script.py > /logfile.log 2>&1
ret=$?
if [ $ret -ne 0 ]; then
     exit $ret
fi

要将脚本结果输出到屏幕和日志文件:

To output the result of the script to the screen and a log file:

Python script.py 2>&1 | tee /logfile.log 

我想组合这2个命令,以便脚本将输出到屏幕和日志文件,并且还捕获1的退出代码以在脚本失败时中止脚本.我尝试以不同的方式组合它们,但是脚本要么继续运行,要么什么都没有输出到屏幕.可以这样做吗?

I want to combine these 2 commands so that the script will output to the screen and log file, and will also catch the exit code of 1 to abort the script when it fails. I tried combining them in different ways, but the script either continues running, or nothing is output to the screen. Is it possible to do this?

推荐答案

使用数组PIPESTATUS:

Use array PIPESTATUS:

Python script.py 2>&1 | tee /logfile.log
ret="${PIPESTATUS[0]}"
if [[ "$ret" -ne "0" ]]; then
  exit "$ret"
fi

来自man bash:

PIPESTATUS:一个数组变量(请参见下面的数组),其中包含最 最近执行的前台管道(可能仅包含一个命令).

PIPESTATUS: An array variable (see Arrays below) containing a list of exit status values from the processes in the most- recently-executed foreground pipeline (which may contain only a single command).

这篇关于在bash脚本输出中捕获退出代码以显示并登录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆