天天看點

shell 知識點補充(6)-exit/expr

1、Linux指令之exit - 退出目前shell

用途說明

退出目前shell,在shell腳本中可以終止目前腳本執行,不退出的話,可能會繼續執行後面的程式。

常用參數

格式:exit n

退出。設定退出碼為n。(Cause the shell to exit with a status of n.)

格式:exit

last 

格式:$?

上一個指令的退出碼。

格式:trap "commands" EXIT

退出時執行commands指定的指令。( A trap on EXIT is executed before the shellterminates.)

退出碼(exit status,或exit code)的約定:

0表示成功(Zero - Success)

2表示用法不當(Incorrect Usage)

127表示指令沒有找到(Command Not Found)

126表示不是可執行的(Not an executable)

>=128 信号産生

當你 exit 0 的時候,在調用環境  echo $?    就傳回0,也就是說調用環境就認為你的這個程式執行正确

當你 exit 1 的時候,一般是出錯定義這個1,也可以是其他數字,很多系統程式這個錯誤編号是有約定的含義的。 但不為0  就表示程式運作出錯。 調用環境就可以根據這個傳回值判斷 你這個程式運作是否ok。

如果你用 腳本 a  調用 腳本b ,要在a中判斷b是否正常傳回,就是根據  exit 0   or  1 來識别。

執行完b後, 判斷  $?   就是傳回值

使用示例      
示例一 退出目前shell      
[root@new55 ~]# 
[root@new55 ~]# exit 
logout      
示例二 在腳本中,進入腳本所在目錄,否則退出      
Bash代碼        
cd $(dirname $0) || exit 1      
示例三 在腳本中,判斷參數數量,不比對就列印使用方式,退出      
Bash代碼  " exit 2 fi" quality="high" allowscriptaccess="always"type="application/x-shockwave-flash"pluginspage="http://www.macromedia.com/go/getflashplayer">       
if [ "$#"-ne "2"]; then      
echo "usage: $0 <area> <hours>"      
exit 2      
fi      
示例四 在腳本中,退出時删除臨時檔案      
Bash代碼        
trap "rm -f tmpfile; echo Bye."EXIT      
示例五 檢查上一指令的退出碼      
Bash代碼        
./mycommand.sh      
EXCODE=$?      
if [ "$EXCODE"== "0"]; then      
echo "O.K"      
fi      

2、expr 指令

對整數型變量進行算術運算

expr 3 + 5    有空格

expr $var1 -  5

expr $var1 /  $var2         除法

expr $var1 \*  10      乘法     要轉義字元