2017-05-26 152 views
0

我在Linux shell中同时运行多个命令,例如,将多个命令的输出重定向到一个文件

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

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

回答

3
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 
0

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

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

将任何东西套入'printf'是徒劳无益的,因为它没有从标准输入读取数据。 – codeforester

+1

@codeforester我的不好,我的意思是'xargs printf'。固定。 –

3

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

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

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

+1

只是一个解释说明...这基本上是一个*“复合语句”*在当前shell中,而不是一个新的子shell或进程。 –

相关问题