Bash: how to redirect stdin / stderr and then return fd?

I want the script to redirect stdin and stderr to a file, do a bunch of things, then cancel these redirects and take action on the contents of the file. I'm trying to:

function redirect(){ exec 3>&1 exec 4>&2 exec 1>outfile 2>&1 } function undirect(){ exec 1>&3 exec 2>&4 } echo first redirect echo something cat kjkk undirect if some_predicate outfile; then echo ERROR; fi 

It seems that I am doing what I want, but it seems rather complicated. Is there a cleaner / clearer way to do this?

+7
source share
2 answers

If you really need to switch it back and forth without knowing in advance what will be, where and when, this is pretty much the way to do it. Depending on your requirements, although it may be more neat to isolate parts that need redirection and execute them as a group, for example:

 echo first { echo something cat kjkk } 1>outfile 2>&1 if some_predicate outfile; then echo ERROR; fi 

{} is called a group command, and the output of the entire group is redirected. If you prefer, you can do your execs in a subshell, since this only affects the subshell.

 echo first ( exec 1>outfile 2>&1 echo something cat kjkk ) if some_predicate outfile; then echo ERROR; fi 

Please note that here I am using parentheses () , not curly braces {} (which were used in the first example).

NTN

+8
source

I think it's pretty clean. The only thing I would like to pass the name "outfile" as a parameter to the function, since you use the file name outside the function

 redirect() { exec 3>&1 exec 4>&2 exec 1>"$1" 2>&1 } : redirect outfile : if some_predicate outfile; ... 
+3
source

All Articles