I have the following code (simplified):
if ! sudo -u user command1 "$Options" -o1 -o2 2>>"$log" > "$Dir"/output;
However, in some cases (determined at run time, if a variable docker is set to true), I instead want to execute
if ! docker exec -t "$cont" command2 "$Options" -o1 -o2 2>>"$log" > "$Dir"/output;
What changes is the way to call the command (1 or 2). The rest of the parameters remain the same.
So I'd like to parametrize the call to command1 or command2.
Something like
if $docker then;
Command = docker exec -t "$cont" command2
else
Command = sudo -u user command1
if ! $Command "$Options" -o1 -o2 2>>"$log" > "$Dir"/output;
This does not work. Is it possible to achieve what I want without resorting to eval
, which I understood to be a bad practice ?
Thanks
CodePudding user response:
You can use an array to hold the command-specific part, and rely on word splitting to build the entire command line to run. Something like
#!/usr/bin/env bash
# Set up your assorted variables used below
if $docker; then
cmd=(docker exec -t "$cont" command2)
else
cmd=(sudo -u user command1)
fi
if ! "${cmd[@]}" "$Options" -o1 -o2 2>>"$log" > "$Dir"/output; then
# etc.
fi