Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to parametrize a function call in bash without using eval?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading