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个参数

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