I would like to use a string as an operator:
if [[ "$show_output" = "yes" ]]; then
redirect_cmd_str=' 2>&1 | tee -a'
else
redirect_cmd_str=' &>>'
fi
$my_command $redirect_cmd_str $my_log
Is it possible in shell/bash?
I would like to use a string as an operator:
if [[ "$show_output" = "yes" ]]; then
redirect_cmd_str=' 2>&1 | tee -a'
else
redirect_cmd_str=' &>>'
fi
$my_command $redirect_cmd_str $my_log
Is it possible in shell/bash?
Shell syntax doesn't support this kind of usage. It's possible to achieve with eval
but I recommend you avoid eval
. Using it is a bad habit that can very easily lead to exploitable holes. From a security perspective it's very, very tricky to use eval
safely.
Rather than storing code in a variable, a better tool for the job is a function:
maybe_show() {
if [[ $show_output = yes ]]; then
"$@" 2>&1 | tee -a "$my_log"
else
"$@" &>> "$my_log"
fi
}
Then you simply prepend any command with the function name:
maybe_show my_command arg1 arg2 arg3
($my_command
shouldn't be a variable either. It can also be a function if it does something dynamic.)
There is the eval solution:
eval "$my_command $redirect_cmd_str $my_log"
but this is not the best solution as comments suggest.