2016-03-06 88 views
0

比方说一个程序,在故障的情况下,输出在成功的情况下的零或1,这样:查看退出代码(程序退出后)

main() { 
    if (task_success()) 
     return 0; 
    else 
     return 1; 
} 

类似与Python,如果您执行exit(0)或exit(1)来指示运行脚本的结果。当你在shell中运行时,你怎么知道程序输出的内容。我试过这个:

./myprog 2> out 

但我没有在文件中得到结果。

+0

在程序中使用打印命令。 –

+0

想象一下,你是一个程序。你的*输出*是你在生活中所说和所写的东西。你的*退出代码*是你死后去天堂还是去地狱。 –

+0

[退出基于进程退出代码的Shell脚本]的可能重复(http://stackoverflow.com/questions/90418/exit-shell-script-based-on-process-exit-code) – tod

回答

4

命令的output与命令的退出代码之间有区别。

您运行的内容./myprog 2> out捕获命令的stderr,而不是上面显示的退出代码。

如果你想在bash/shell中检查一个程序的退出代码,你需要使用$?操作符来捕获最后一个命令的退出代码。

例如:

./myprog 2> out 
echo $? 

会给你命令的退出代码。

BTW, 用于捕获命令的输出,您可能需要使用1为您的重定向,其中1捕捉stdout2捕捉stderr

0

命令的返回值存储在$?中。当你想用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