问题
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?
回答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
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
回答2:
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:
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
来源:https://stackoverflow.com/questions/44192376/redirect-outputs-of-multiple-commands-to-a-file