The most expansible and robust way would probably be to use an array to hold the optional parameter(s):
params=()
if [[ $CONDITION == true ]]; then
params+=(--param2)
fi
script param1 "${params[@]}"
Or in shorthand:
[[ $CONDITION == true ]] && params+=(--param2)
script param1 "${params[@]}"
That avoids repeating the constant part of the command and you can put more than one argument in the array, even the whole command.
Note that it's important to do this with an array: if you replace the array with a regular variable (params="--param2"; script param1 $params
) you'll either have to expand the variable unquoted, with all the problems that brings, or expand it quoted, in which case you'll pass an empty string as argument if the variable is empty.
In a simple case like this, the "alternate value" expansion can also be used:
cond=x
p2="--param2"
script param1 ${cond:+"$p2"}
Here, if cond
is nonempty (regardless of if it's cond=false
or cond=0
instead of cond=true
), the value of p2
is expanded. This may be seen as less ugly than arrays, but be careful with the placement of the quotes.
See also:
if
? In the script itself? In another script that calls the target script? Are these options (--param2
) or arguments (param1
)? Please [edit] your question and give us more details. – terdon May 30 '18 at 08:17true
is a shell builtin that returns a success exit status. If you useCONDITION=false
when CONDITION is not true, then you could write:if "$CONDITION"; then echo yes; fi
or"$CONDITION" && echo yes
– glenn jackman May 30 '18 at 19:21true
is not the same as"true"
right? – Jim May 30 '18 at 20:40"echo" "foo"
with no difficulty because the shell will remove the quotes before executing the command. – glenn jackman May 30 '18 at 20:44valid=false
if someCondition; then valid=true; fi;
if ! $valid; then echo Invalid; exit 1; fi
– glenn jackman May 30 '18 at 20:47true
? I just need a boolean indicator – Jim Jun 09 '18 at 15:01true
andfalse
are commands built into the shell. Their only purpose is to return a success or failure exit status. Soif $valid; then echo true; else echo false; fi
where "valid" holds either "true" or "false" will execute the expected branch of the if statement. Therefore, the example I showed is a boolean indicator. – glenn jackman Jun 09 '18 at 15:10