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

2vuwiymt  于 12个月前  发布在  Shell
关注(0)|答案(2)|浏览(154)

嗨下面是我的代码bash shell脚本,在这我想捕捉错误信息,如果子句,当它说,无论是作业已经运行或无法启动作业到一个变量,它是如何可能在下面的脚本,或任何其他方式为下面的功能

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

im9ewurl1#

例如,您可以使用语法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

它使用How to pipe stderr, and not stdout?,因此它从initctl start $i捕获stderr并存储在$error变量中。
然后,$?包含命令的返回代码,如How to check if a command succeeded?所示。如果0,则成功;否则,就会出现一些错误。

wz3gfoph

wz3gfoph2#

使用'$?'变量它存储上一条语句中的任何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

相关问题