zsh:参数扩展插入引号

t-m*_*art 4 parameters quotes zsh expansion

我在 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
    }
Run Code Online (Sandbox Code Playgroud)

需要明确的是,在该find行中,我希望这样:如果recurse为 null,则替换-maxdepth 1。如果recurse设置为t,则不替换任何内容(即让 find 执行正常的递归行为)。

看起来可能有点奇怪,因为虽然这只是形式${name:-word},但word实际上以连字符开头。(在这里查看更多信息http://zsh.sourceforge.net/Doc/Release/Expansion.html#Parameter-Expansion

相反,发生的情况是,如果recurse为 null,则替换"-maxdepth 1"(注意周围的引号),如果recurse设置,则替换""

不递归时的确切错误是 find: unknown predicate `-maxdepth 1'. 你可以自己尝试一下,只find "-maxdepth 1"举例说明。当我们确实想要递归时,会发生一些奇怪的事情,我无法完全解释,但错误是find `t': No such file or directory

有谁知道如何使 zsh 在此参数扩展中不添加引号?我相信这是我的问题。

谢谢。

qqx*_*qqx 6

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
Run Code Online (Sandbox Code Playgroud)

因此,您可以通过设置该选项setopt sh_word_split,导致对所有参数扩展进行拆分,或者您可以使用以下命令显式请求该扩展:

${=recurse:--maxdepth 1}
Run Code Online (Sandbox Code Playgroud)

请注意该=符号是大括号内的第一个字符。手册页中也指出了这一点zshexpn,搜索${=spec}.