[Shell Script] Exit code

每個指令都會返回一個Exit Status, 通常稱之為Exit code或Return code
Return code的範圍從0-255
其中 0 代表執行成功success
其他不是 0 的數字都是error condition

如何看Return code呢?
$? 代表了前一個執行指令的Return Code

ls /folderNotExisted
ls: cannot access '/folderNotExisted': No such file or directory

echo "$?"
2

寫一個 exiCode.sh

#!/bin/bash
HOST="google.com"
ping -c 1 $HOST && echo -e "\n $HOST reachable."

結果:

PING google.com (216.58.200.238) 56(84) bytes of data.
64 bytes from redirector.googlevideo.com (216.58.200.238): icmp_seq=1 ttl=54 time=17.7 ms

--- google.com ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 17.739/17.739/17.739/0.000 ms

 google.com reachable.

發表留言