2

I am calling a bash script that has a number of flags in the following manner:

/home/username/myscript -a -b 76

So to illustrate, the -a flag does something in myscript and the -b flag sets some parameter to 76 in myscript.

How do I make these flags conditional based on some previously defined variable? For example, I only want to use the -a flag if some variable var=ON, else I don't what to use that flag. I am looking for something like:

var=ON
/home/username/myscript 
if [ "$var" == "ON" ]; then
-a
fi
-b 76

This scheme did not work when implemented, however. What can be used to accomplish the desired result?

1

2 Answers 2

9

You can build the command in an array:

#!/bin/bash
var=ON
cmd=( /home/username/myscript )   # create array with one element
if [ "$var" == "ON" ]; then
    cmd+=( -a )                   # append to the array
fi
cmd+=( -b 76 )                    # append two elements

And then run it with:

"${cmd[@]}"

Note the quotes around the last part, and the parenthesis around the assignments above. The syntax is ugly, but it works in the face of arguments containing white space and such. (Use quotes to add arguments with spaces, e.g. cmd+=("foo bar"))

Related, with less ugly methods and ways they can fail:


In simple cases, like that one optional argument here, you could get away with the alternate value expansion:

var=x
myscript ${var:+"-a"} -b 76

Here, ${var:+foo} inserts foo if var is not empty (so var=ON, var=FALSE, var=x would all insert it), and nothing if it is empty or unset (var=, or unset var). Be careful with the usual quoting issues.

3
  • 2
    +1 This syntax is ugly and it is more complex, but the solution is scalable, while my solution is simpler but would rapidly evolve to a mess if more flags combinations were to be considered.
    – Quasímodo
    May 25, 2020 at 19:42
  • Thanks! Exactly what I'm looking for!
    – theta
    May 25, 2020 at 19:44
  • 1
    @theta, added another option, one less ugly and more prone to getting messy if expanded.
    – ilkkachu
    May 25, 2020 at 19:56
1

If I understand you correctly:

var=ON
if [ "$var" = "ON" ]; then
    /home/username/myscript -a -b 76
else
    /home/username/myscript -b 76
fi

Not the answer you're looking for? Browse other questions tagged .