
我之前發現了一個 Bash 腳本片段,用於將字串回顯到 stderr:
echoerr() { echo "$@" 1>&2; }
echoerr hello world
這仍然在我的剪貼簿中,當我想編輯檔案(使用 VIM)時,我不小心再次貼上了這個片段而不是檔案名稱:
vim echoerr() { echo "$@" 1>&2; }
echoerr hello world
它似乎已重新分配echoerr
給vim
:
$ where vim
vim () {
echo "$@" 1>&2;
}
/usr/bin/vim
另外,嘗試使用 VIM 開啟檔案現在只會回顯檔案名稱:
vim path/to/some-file
印刷:
path/to/some-file
發生了什麼事?(我在 tmux 內運行 zsh)
答案1
因為zsh
允許您定義具有多個名稱的函數。從man zshmisc
:
function word ... [ () ] [ term ] { list }
word ... () [ term ] { list }
word ... () [ term ] command
where term is one or more newline or ;. Define a function which
is referenced by any one of word. Normally, only one word is
provided; multiple words are usually only useful for setting
traps. The body of the function is the list between the { and
}. See the section `Functions'.
答案2
您已經成功建立了一個名為 的函數vim()
。這是可能的,因為 zsh 允許您同時建立具有多個名稱的單一函數
% vim dud() { echo ran dud function }
% dud
ran dud function
% vim path/to/some-file
ran dud function
請注意如何將vim()
和dud()
兩者設定為函數。
您可以透過取消設定它的函數 def 來殺死錯誤的函數,如下所示:
% unset -f vim
現在vim path/to/some-file
應該打開你的編輯器。