I have a whole bunch of tests on variables in a bash (3.00) shell script where if the variable is not set, then it assigns a default, e.g.:
if [ -z "${VARIABLE}" ]; then
FOO='default'
else
FOO=${VARIABLE}
fi
I seem to recall there's some syntax to doing this in one line, something resembling a ternary operator, e.g.:
FOO=${ ${VARIABLE} : 'default' }
(though I know that won't work...)
Am I crazy, or does something like that exist?
For command line arguments:
which assigns to
VARIABLE
the value of the 1st argument passed to the script or the value ofDEFAULTVALUE
if no such argument was passed.see here under 3.5.3(shell parameter expansion)
so in your case
Here is an example
save this as script.sh and make it executable. run it without params
run it with param
Then there's the way of expressing your 'if' construct more tersely:
Even you can use like default value the value of another variable
having a file
defvalue.sh
run
./defvalue.sh first-value second-value
outputand run
./defvalue.sh first-value
outputVery close to what you posted, actually:
Or, which will assign
default
toVARIABLE
as well: