2016-03-06 56 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