
在 bash 中我看到which
按順序返迴路徑,但在 zsh 中它有不同的順序。
我現在主要使用 zsh,如何which
在 zsh 中獲得正確的輸出排序?為什麼不一樣呢?我希望順序符合我的路徑。
我的路徑是:/usr/local/bin:/usr/bin
bash$ which -a git
/usr/local/bin/git
/usr/bin/git
zsh$ which -a git
/usr/bin/git
/usr/local/bin/git -> ../Cellar/git/2.32.0/bin/git
答案1
你碰巧定義which
為:
which(){
/usr/bin/which -a "$@" |
xargs ls -l |
tr -s ' ' |
cut -d ' ' -f 9-
}
ls
在輸出中按詞法對檔案名稱進行排序並位於後面,因為/usr/local/bin/git
/usr/bin/git
l
緊接著b
在您的語言環境中。
GNU 實作ls
有一個-U
選項可以停用該排序。
您的/usr/bin/which
命令似乎是一個列印$PATH
傳遞選項時找到的所有命令名稱的路徑的命令-a
。對於zsh
內建函數,您可以使用 ¹ 執行相同的操作whence -pa
。
所以你可以這樣做:
mywhich() (
set -o pipefail
zmodload zsh/stat
whence -pa "$@" |
while IFS= read -r f; do
if [[ -L $f ]] && stat -A l +link -- $f; then
print -r -- "$f -> $l"
else
print -r -- $f
fi
done
)
(這裡假設所有檔案路徑都不包含換行符號)。
在 GNU 系統上,你的更正確的版本將是這樣的:
mywhich() (
set -o pipefail
command which -a "$@" |
xargs -rd '\n' ls -ndU -- |
sed -E 's/([^ ]+ +){8}//'
)
無論如何,請注意它bash
沒有which
內建函數,因此which
輸出內容與 shell 無關。只有tcsh
並且zsh
有which
內建的。
1 不過,就像您的/usr/bin/which
(但與 zsh 的builtin 相反which
)一樣,它不一定會告訴您 shell 將運行哪個命令,因為它會忽略別名、函數、內建命令甚至$hash
可執行檔案表。也可以看看為什麼不用「哪個」呢?那該用什麼呢?