Linux Shell 返回值總結

Beforewemoveon,thereisaperversityabouttestsinBashshellsthatIwanttodiscuss.Itturnsout,becauseofahistoricalaccidentthatnowmightaswellbecastinconcrete,whenatestisconductedoracommandreturnsaresultvalue,thenumericalvaluefor"true"is0,and"false"is1.ThoseofyouwhohavesomeprogrammingexperiencewilllikelyfindthisreversalofintuitionasannoyingasIdo.

Hereisawaytogettheresultofthemostrecentlogicaltest(andtoshowtheweirdreversaldescribedabove):

其實就是上一次程序或腳本的退出碼,主要是用來判斷程序或腳本的執行是否成功,檢查出錯的原因之類的。一般情況下,在linux/unix下編程時,我們會在應用程序退出時返回一個整型數據(在main函數中通過return/exit,或者別的函數/方法中exit)。這個返回值是給SHELL使用的,因爲我們可能需要了解應用程序的執行狀態,然後根據不同的執行狀態去執行不同的分支(類似於函數的返回值)。


$test-e
$echo$?
0

$test-exyz
$echo$?
1

[root@LABRH~]#test2-gt3
[root@LABRH~]#echo$?
1
[root@LABRH~]#test3-gt2
[root@LABRH~]#echo$?
0

$n$1thefirstparameter,$2thesecond...
$#Thenumberofcommand-lineparameters.
$0Thenameofcurrentprogram.
$?Lastcommandorfunction'sreturnvalue.
$$Theprogram'sPID.
$!Lastprogram'sPID.
$@Savealltheparameters.

almostanyshellbookwilltalkaboutthem,fromwhichyoucangettheirdetailusages.

$#腳本的參數個數

$*以一個單字符串顯示所有向腳本傳遞的參數

$$腳本運行的當前進程ID號

$!後臺運行的最後一個進程的進程ID號

$@與$*相同,但是使用時加引號,並在引號中返回每個參數

$-顯示shell使用的當前選項

$?顯示最後命令的退出狀態,0表示沒有錯誤,其他任何值表明有錯誤

$0腳本名稱

$1..$9第N個參數

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章