Bash – How to prevent bash command substitution output from being escaped

bashcommand-substitutionshell-script

I am trying to use command substitution in a bash script to output redirection symbols based on a variable like so:

IS_VERBOSE=false
curl $BLAH $( $IS_VERBOSE && echo '-i' || echo '> /dev/null' )

That is, if verbose, add the -i switch, otherwise, throw everything from stdout away. The problem is that when IS_VERBOSE is false, my command becomes

curl $BLAH \> /dev/null

More generally, command substitution escapes the characters > >> & | # $ and possibly others. How can I output these symbols without escaping using command substitution?

Best Answer

After the substition happens (which BTW in POSIX could only target the left side before any ">") there is no more evaluation on whether there is any ">" so the approach you envisioned wouldn't work.

If you don't care about POSIX-conformity (after all you tagged this as 'bash') you could still find a solution by dynamically setting the right side but I would personally go for a totally different approach; have a look at the following post detailing a verbose/silent mode based on custom file descriptors: https://stackoverflow.com/a/20942015/2261442.

A code excerpt from that post to show how nice it would then look like:

# Some confirmations:
printf "%s\n" "This message is seen at verbosity level 3 and above." >&3
printf "%s\n" "This message is seen at verbosity level 4 and above." >&4
printf "%s\n" "This message is seen at verbosity level 5 and above." >&5
Related Question