Bash – Use a Variable to Store stderr|stdout Redirection

bashbrace-expansionio-redirectionstdout

Is there any way to redirect stdout and stderr via variable like adding command options in script?

For example I have a script:

#!/bin/bash -x
TEST=">/dev/null 2>&1"
OPT='-p -v'
mkdir $OPT 123/123/123 $TEST

I can see that OPT is replaced with -p without any problems and bash interprets it as option. But redirection interprets as directories name.

$ ./test.sh 
+ TEST='>/dev/null 2>&1'
+ OPT='-p -v'
+ mkdir -p -v 123/123/123 '>/dev/null' '2>&1'
mkdir: created directory `123/123'
mkdir: created directory `123/123/123'
mkdir: created directory `>/dev'
mkdir: created directory `>/dev/null'
mkdir: created directory `2>&1'

Is there any way to say bash, that $VAR is redirection, not a dirs names.

PS. May be I'm on wrong way, but I want to make optional verbose or non verbose output from my script. But I need some output even in non-verbose mode, therefore I can't just redirect whole stdout and stderr, only from some commands inside of my script.

Best Answer

Another solution could be the following:

#!/bin/bash

verbose=0

exec 3>&1
exec 4>&2

if ((verbose)); then
  echo "verbose=1"
else
  echo "verbose=0"
  exec 1>/dev/null
  exec 2>/dev/null
fi

echo "this should be seen if verbose"
echo "this should always be seen" 1>&3 2>&4

Then add 1>&3 2>&4 only to commands of which you want to see the output.

Related Question