【问题标题】:Redirect outputs of multiple commands to a file将多个命令的输出重定向到文件
【发布时间】:2017-05-26 01:50:41
【问题描述】:

我同时在我的 Linux shell 中运行多个命令,例如

echo "Line of text 1" && echo "Line of text 2" && complexthing | xargs printf "complexspecifier"

我想将所有输出重定向到file1。我知道我可以在每个单独的命令之后添加>file1,但这看起来很笨重。我该怎么做?

【问题讨论】:

    标签: bash shell command-line syntax output


    【解决方案1】:
    exec >file1   # redirect all output to file1
    echo "Line of text1"
    echo "Line of text2"
    exec > /dev/tty  # direct output back to the terminal 
    

    或者,如果您在没有/dev/tty 的机器上,您可以这样做:

    exec 5>&1 > file1  # copy current output and redirect output to file1 
    echo foo
    echo bar
    exec 1>&5 5>&-  # restore original output and close the copy
    

    【讨论】:

    • 对于相对的菜鸟:在这个例子中5 是什么?为什么是5 而不是64?有一个文档链接也很棒。谢谢。
    • @Leonid 没有理由选择 5 而不是 6 或 4。只要您选择一个尚未使用的文件描述符。
    【解决方案2】:

    如果您不需要在子 shell 中运行命令,可以使用 { ... } > file:

    { echo "Line of text 1" && echo "Line of text 2" && complexthing | xargs printf "complexspecifier"; } > file1
    

    请注意,{ 后面需要一个空格,} 前面需要一个分号,除非最后一个命令后面有 & 或换行符。

    【讨论】:

    • 只是一个解释说明......这基本上是当前shell中的“复合语句”,而不是新的子shell或进程。
    • 注意右括号前的;。重要的是不要忘记它,例如在管道 2 个命令时:-)
    【解决方案3】:

    想通了。您可以在命令周围使用括号,然后附加 >file1:

    (echo "Line of text 1" && echo "Line of text 2" && complexthing | xargs printf "complexspecifier") >file1
    

    【讨论】:

    • 将任何内容导入printf 是徒劳的,因为它不会从其标准输入中读取。
    • @codeforester 我的错,我的意思是xargs printf。固定。
    • 括号导致命令在单独的子shell中运行,这可能有用也可能没有用和必要。您可能应该了解{ ...; }( ... ) 之间的区别,然后对使用哪一个做出明智的选择。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-07
    • 1970-01-01
    • 1970-01-01
    • 2015-10-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多