【问题标题】:Can I specify redirects and pipes in variables?我可以在变量中指定重定向和管道吗?
【发布时间】:2010-09-12 20:15:27
【问题描述】:

我有一个 bash 脚本,它为当前目录创建一个 Subversion 补丁文件。如果-z 作为脚本的参数,我想修改它以压缩生成的文件。

以下是相关部分:

zipped=''
zipcommand='>'

if [ "$1" = "-z" ]
then
   zipped='zipped '
   filename="${filename}.zip"
   zipcommand='| zip >'
fi

echo "Creating ${zipped}patch file $filename..."

svn diff $zipcommand $filename

这不起作用,因为它将$zipcommand 中包含的|> 作为参数传递给svn

我可以轻松解决这个问题,但问题是当它们包含在变量中时是否可以使用这些类型的运算符。

谢谢!

【问题讨论】:

    标签: bash


    【解决方案1】:

    我会做这样的事情(使用 bash -c 或 eval):

    zipped=''
    zipcommand='>'
    
    if [ "$1" = "-z" ]
    then
       zipped='zipped '
       filename="${filename}.zip"
       zipcommand='| zip -@'
    fi
    
    echo "Creating ${zipped}patch file $filename..."
    
    eval "svn diff $zipcommand $filename"
    # this also works: 
    # bash -c "svn diff $zipcommand $filename"
    

    这似乎可行,但我的 zip (Mac OS X) 版本要求我更改行:

    zipcommand='| zip -@'
    

    zipcommand='| zip - - >'
    

    编辑:合并@DanielBungert 使用 eval 的建议

    【讨论】:

    • 谢谢!是的,我最初有错误的 zip 参数,因为我已经从一个脚本中改编了这个,该脚本将“svn status”给出的文件通过管道传输到从标准输入读取文件名的“zip -@”。
    【解决方案2】:

    eval 就是你要找的东西。

    # eval 'printf "foo\nbar" | grep bar'
    bar
    

    请注意上面的引号字符。

    【讨论】:

      【解决方案3】:

      或者你应该尝试zsh shell,它允许定义全局别名,例如:

      alias -g L='| less'
      alias -g S='| sort'
      alias -g U='| uniq -c'
      

      然后使用这个命令(对于那些从后面看的人来说有点神秘;-))

      ./somecommand.sh S U L
      

      HTH

      【讨论】:

        【解决方案4】:

        在处理压缩的进程替换或命名文件上打开一个新文件句柄。然后将svn diff 的输出重定向到该文件句柄。

        if [ "$1" = "-z" ]; then
            zipped='zipped '
            filename=$filename.zip
            exec 3> >(zip > "$filename")
        else
            exec 3> "$filename"
        fi
        
        echo "Creating ${zipped}patch file $filename"
        svn diff >&3
        

        【讨论】:

          猜你喜欢
          • 2022-01-07
          • 1970-01-01
          • 2012-03-22
          • 2023-04-03
          • 1970-01-01
          • 2015-01-03
          • 1970-01-01
          • 2020-03-19
          相关资源
          最近更新 更多