将多个命令的输出重定向到一个文件

3

我正在同时运行多个Linux shell命令,例如:

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

我希望将所有输出重定向到file1文件。我知道可以在每个单独的命令后面添加>file1,但这样看起来很笨重。有什么更好的方法吗?

3个回答

9
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是什么?为什么不是64?如果有文档链接就更好了。谢谢。 - Leonid
1
@Leonid 没有理由选择5而不是6或4。只要选择一个尚未被使用的文件描述符即可。 - William Pursell

9
如果您不需要在子shell中运行命令,您可以使用{ ... } > file
{ echo "Line of text 1" && echo "Line of text 2" && complexthing | xargs printf "complexspecifier"; } > file1

请注意,除非在最后一个命令之后有&或换行符,否则您需要在{后面添加空格并在}前添加分号。

2
只是一个解释说明……这基本上是当前 shell 中的“复合语句”,而不是一个新的子 shell 或进程。 - Mark Setchell
请注意在右括号前的分号;。重要的是不要忘记它,例如当管道连接两个命令时 :-) - hornetbzz

3
弄清楚了。您可以在命令周围使用括号,然后附加>file1
(echo "Line of text 1" && echo "Line of text 2" && complexthing | xargs printf "complexspecifier") >file1

将任何内容传输到 printf 中是徒劳的,因为它不会从其标准输入读取。 - codeforester
1
@codeforester 我的错,我是指 xargs printf。已修正。 - MD XF
括号会导致命令在单独的子shell中运行,这可能有用也可能是必要的。你应该了解{ ...; }( ... )之间的区别,然后做出明智的选择。 - tripleee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接