Redirect outputs of multiple commands to a file

旧城冷巷雨未停 提交于 2019-12-19 10:57:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!