我嘗試了如下的寫法,不知道錯誤在哪里if [ -n `which brew`]; then
echo 'brew exist'else
echo 'brew does not exist'fi用來判斷brew命令是否存在,可是明明沒有brew,卻總是顯示 "brew exist"
3 回答

ABOUTYOU
TA貢獻1812條經驗 獲得超5個贊
最好避免使用 which,做為一個外部的工具,并不一定存在,在發行版之間也會有區別,有的系統的 which 命令不會設置有效的 exit status,存在一定的不確定性。
Bash 有提供一些內建命令如 hash、type、command 也能達到要求。
$ command -v foo >/dev/null 2>&1 || { echo >&2 "I require foo but it's not installed. Aborting."; exit 1; } $ type foo >/dev/null 2>&1 || { echo >&2 "I require foo but it's not installed. Aborting."; exit 1; } $ hash foo 2>/dev/null || { echo >&2 "I require foo but it's not installed. Aborting."; exit 1; }

慕田峪4524236
TA貢獻1875條經驗 獲得超5個贊
which want_to_find > /dev/null 2>&1if [ $? == 0 ]; then echo "exist"else echo "dose not exist"fi

慕的地8271018
TA貢獻1796條經驗 獲得超4個贊
if hash brew 2>/dev/null; then
echo 'brew exist'
else
echo 'brew does not exist'
fi
Hash是一個緩存表
系統初始Hash表是空的,如果系統重啟也會清空,當外部命令執行是會到PATH里找該命令,然后記錄在Hash里,當再執行時就到Hash里取,這樣會加快執行速度。
- 3 回答
- 0 關注
- 179 瀏覽
添加回答
舉報
0/150
提交
取消