[英]zsh: parameter expansion inserting quotes
我在zsh中的參數擴展期間遇到了麻煩:它將我的變量括在引號中。
這是我的劇本。 (對於噪音道歉,唯一真正重要的一行是find
調用的最后一行,但我想確保我沒有隱藏我的代碼的詳細信息)
#broken_links [-r|--recursive] [<path>]
# find links whose targets don't exist and print them. If <path> is given, look
# at that path for the links. Otherwise, the current directory is used is used.
# If --recursive is specified, look recursively through path.
broken_links () {
recurse=
search_path=$(pwd)
while test $# != 0
do
case "$1" in
-r|--recursive)
recurse=t
;;
*)
if test -d "$1"
then
search_path="$1"
else
echo "$1 not a valid path or option"
return 1
fi
;;
esac
shift
done
find $search_path ${recurse:--maxdepth 1} -type l ! -exec test -e {} \; -print
}
為了清楚-maxdepth 1
,在find
行中,我想這樣:如果recurse
為null,則替換-maxdepth 1
。 如果recurse
設置為t
,則不替換任何內容(即讓我們發現它是正常的遞歸行為)。
看起來可能有點奇怪,因為盡管這只是${name:-word}
形式,但實際上word
以連字符開頭。 (詳情請見http://zsh.sourceforge.net/Doc/Release/Expansion.html#Parameter-Expansion )
相反,正在發生的事情是,如果recurse
為null,它將替換"-maxdepth 1"
(注意周圍的引號),如果設置了recurse
,則替換為""
。
不find: unknown predicate `-maxdepth 1'
時的確切錯誤是find: unknown predicate `-maxdepth 1'
。 你可以自己試試這個,例如find "-maxdepth 1"
。 當我們想要遞歸時,發生了一些奇怪的事情,我無法解釋,但錯誤是find `t': No such file or directory
。
有誰知道如何讓zsh不在這個參數擴展中放置引號? 我相信這是我的問題。
謝謝。
zsh實際上並沒有添加引號,它只是沒有對參數擴展的結果進行單詞拆分。 這是默認情況下記錄的行為方式。 從參數擴展部分開頭附近的zshexpn
手冊頁:
Note in particular the fact that words of unquoted parameters are not
automatically split on whitespace unless the option SH_WORD_SPLIT is set
因此,您可以通過執行setopt sh_word_split
來設置該選項,從而導致對所有參數擴展執行拆分,或者您可以使用以下命令顯式請求它以進行擴展:
${=recurse:--maxdepth 1}
注意=
符號作為大括號內的第一個字符。 這也在zshexpn
手冊頁中注明,搜索${=spec}
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.