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.true
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
true
is not the same as"true"
right?"echo" "foo"
with no difficulty because the shell will remove the quotes before executing the command.valid=false
if someCondition; then valid=true; fi;
if ! $valid; then echo Invalid; exit 1; fi