Redirect outputs of multiple commands to a file

2020-03-08 05:11发布

I'm running multiple commands in my Linux shell at the same time, e.g.

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

I want to redirect all output to file1. I know I can add >file1 after each individual command but this seems bulky. How can I do this?

3条回答
不美不萌又怎样
2楼-- · 2020-03-08 05:55

If you don't need to run your commands in a subshell, you could use { ... } > file:

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

Note that you need a space after { and a semicolon before }, unless you have an & or a newline after the last command.

查看更多
在下西门庆
3楼-- · 2020-03-08 06:05
exec >file1   # redirect all output to file1
echo "Line of text1"
echo "Line of text2"
exec > /dev/tty  # direct output back to the terminal 

Or, if you are on a machine that doesn't have /dev/tty, you can do:

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
查看更多
Summer. ? 凉城
4楼-- · 2020-03-08 06:07

Figured it out. You can use parenthesis around the commands, then append >file1:

(echo "Line of text 1" && echo "Line of text 2" && complexthing | xargs printf "complexspecifier") >file1
查看更多
登录 后发表回答