查看退出代码(程序退出后)
问题描述:
比方说一个程序,在故障的情况下,输出在成功的情况下的零或1,这样:查看退出代码(程序退出后)
main() {
if (task_success())
return 0;
else
return 1;
}
类似与Python,如果您执行exit(0)或exit(1)来指示运行脚本的结果。当你在shell中运行时,你怎么知道程序输出的内容。我试过这个:
./myprog 2> out
但我没有在文件中得到结果。
答
命令的返回值存储在$?
中。当你想用returncode做一些事情时,最好在调用另一个命令之前将它存储在一个变量中。另一个命令将在$?
中设置新的返回码。
在下一个代码中,echo
将重置$?
的值。
rm this_file_doesnt_exist
echo "First time $? displays the rm result"
echo "Second time $? displays the echo result"
rm this_file_doesnt_exist
returnvalue_rm=$?
echo "rm returned with ${returnvalue}"
echo "rm returned with ${returnvalue}"
如果您对stdout/stderr感兴趣,也可以将它们重定向到一个文件。您还可以将它们捕获到一个shell变量中,并使用它进行一些操作:
my_output=$(./myprog 2>&1)
returnvalue_myprog=$?
echo "Use double quotes when you want to show the ${my_output} in an echo."
case ${returnvalue_myprog} in
0) echo "Finally my_prog is working"
;;
1) echo "Retval 1, something you give in your program like input not found"
;;
*) echo "Unexpected returnvalue ${returnvalue_myprog}, errors in output are:"
echo "${my_output}" | grep -i "Error"
;;
esac
在程序中使用打印命令。 –
想象一下,你是一个程序。你的*输出*是你在生活中所说和所写的东西。你的*退出代码*是你死后去天堂还是去地狱。 –
[退出基于进程退出代码的Shell脚本]的可能重复(http://stackoverflow.com/questions/90418/exit-shell-script-based-on-process-exit-code) – tod