bash 如何在 if 块的变量中捕获命令错误消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25303996/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:07:48  来源:igfitidea点击:

how to capture command error message in variable for if block

linuxbashshell

提问by agarwal_achhnera

Hi below is my code for bash shell script, in this I want to capture error message for if clause, when it says either job is already running or unable to start the job to a variable, how it is possible in below script, or any other way for the below functionality

嗨,下面是我的 bash shell 脚本代码,在此我想捕获 if 子句的错误消息,当它说作业已经在运行或无法启动变量的作业时,在下面的脚本中如何可能,或任何以下功能的其他方式

if initctl start $i  ; then
    echo "service $i  started by script"
else
    echo "not able to start service $i"
fi

回答by fedorqui 'SO stop harming'

You can for example use the syntax msg=$(command 2>&1 1>/dev/null)to redirect stderr to stdout after redirecting stdout to /dev/null. This way, it will just store stderr:

例如,您可以msg=$(command 2>&1 1>/dev/null)在将 stdout 重定向到 /dev/null 之后使用语法将 stderr 重定向到 stdout。这样,它只会存储 stderr:

error=$(initctl start $i 2>&1 1>/dev/null)
if [ $? -eq 0 ]; then
   echo "service $i started by script"
else
   echo "service $i could not be started. Error: $error"
fi

This uses How to pipe stderr, and not stdout?, so that it catches stderr from initctl start $iand stores in $errorvariable.

这使用如何管道 stderr,而不是 stdout?,以便它从变量中捕获 stderrinitctl start $i并存储在$error变量中。

Then, $?contains the return code of the command, as seen in How to check if a command succeeded?. If 0, it succeeded; otherwise, some errors happened.

然后,$?包含命令的返回码,如如何检查命令是否成功?. 如果0,则成功;否则,会发生一些错误。

回答by rurouni88

Use '$?' variable It stores any exit_code from the previous statement See http://www.tldp.org/LDP/abs/html/exitcodes.htmlfor more information

使用“$?” 变量 它存储上一条语句中的任何 exit_code 请参阅http://www.tldp.org/LDP/abs/html/exitcodes.html了解更多信息

initctl start $i
retval=$?
if [ $retval -eq 0 ]; then
    echo "service $i  started by script"
else
    echo "not able to start service $i"
fi