1

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?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
Guillaume D
  • 2,202
  • 2
  • 10
  • 37

2 Answers2

5

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.)

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
  • i like your solution, but could you add example on how i can add ```$show_output``` and ```$my_log``` as arguments? i find it dirty to change variable before function call, but maybe i'm wrong. – Guillaume D Jan 14 '21 at 09:28
  • and why do you use ```"$@"``` instead of ```$@``` ? – Guillaume D Jan 14 '21 at 09:31
  • See [this answer](https://stackoverflow.com/a/3990540/68587): "When the expansion occurs within double quotes, each parameter expands to a separate word. That is, `"$@"` is equivalent to `"$1" "$2" ...`" – John Kugelman Jan 14 '21 at 09:33
  • Handling arguments in a function is the same as handling them in a script. They use the same syntax & tricks. So you can refer to questions like [this one](https://stackoverflow.com/questions/255898/how-to-iterate-over-arguments-in-a-bash-script) for a guide on argument handling. – John Kugelman Jan 14 '21 at 09:41
0

There is the eval solution:

eval "$my_command $redirect_cmd_str $my_log"

but this is not the best solution as comments suggest.

Guillaume D
  • 2,202
  • 2
  • 10
  • 37
  • 2
    [be careful](https://stackoverflow.com/questions/17529220/why-should-eval-be-avoided-in-bash-and-what-should-i-use-instead) when using `eval` ... – Aserre Jan 14 '21 at 09:13