2013-04-24 44 views
0

我在zsh参数扩展期间遇到了麻烦:它将我的变量括在引号中。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 
    } 

只要是明确的,在find线,我想这样:如果recurse为空,替换-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不在这个参数扩展中放置引号?我相信这是我的问题。

谢谢。

回答

2

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}

+0

做到了!谢谢! – 2013-04-25 01:00:17