文章目錄
- 1. 直接執行
- 2. 内建指令
-
- POSIX compatible:
- For Bash specific environments:
- 3. 外部工具
- 參考
1. 直接執行
優點:簡單、直接。
缺點:會啟動程式,對于rm 、python等指令需要加上沒有其它副作用的參數。如檢視版本的參數–version。
# 方法1
ls &> /dev/null
if [ $? -eq 0 ]
then
echo "exist"
fi
# 方法2
if python --version &> /dev/null
then
echo "exist"
fi
2. 内建指令
内建指令相對穩定
POSIX compatible:
- command(相容性更好)
# 方法1
command -v ls &> /dev/null
if [ $? -eq 0 ]
then
echo "exist"
fi
# 方法2
if command -v python &> /dev/null
then
echo "exist"
fi
For Bash specific environments:
- type
- hash
3. 外部工具
-
which
最好避免使用 which,做為一個外部的工具,并不一定存在,在發行版之間也會有差別,有的系統的 which 指令不會設定有效的 exit status,存在一定的不确定性。
-
whereis
與which類似
參考
shell中如何判斷某一指令是否存在
How can I check if a program exists from a Bash script?
How can I check if a command exists in a shell script? [duplicate]
shell程式設計判斷一個指令是否存在?