如何捕获if块的变量中的命令错误消息 [英] how to capture command error message in variable for if block
问题描述
您好,以下是我的bash shell脚本代码,在此我想捕获if子句的错误消息,当它说作业已经在运行或无法将作业启动到变量时,在下面的脚本中怎么可能,或其他任何用于以下功能的方式
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
if initctl start $i ; then
echo "service $i started by script"
else
echo "not able to start service $i"
fi
推荐答案
例如,您可以使用语法 msg = $(command 2>& 1 1>/dev/null)
重定向将stdout重定向到/dev/null后,将stderr转换为stdout.这样,它将只存储stderr:
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:
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
这使用如何用管道输送stderr而不是stdout?,以便从 initctl start $ i
捕获stderr并将其存储在 $ error
变量中.
This uses How to pipe stderr, and not stdout?, so that it catches stderr from initctl start $i
and stores in $error
variable.
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.
这篇关于如何捕获if块的变量中的命令错误消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!