views:

134

answers:

4

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?

Thanks!

A: 

For command line arguments:

VARIABLE=${1:-DEFAULTVALUE}    

#set VARIABLE with the value of 1st Arg to the script,
#If 1st arg is not entered, set it to DEFAULTVALUE
The MYYN
+4  A: 

Very close to what you posted, actually:

FOO=${VARIABLE:-default}

Or, which will assign to VARIABLE as well:

FOO=${VARIABLE:=default}
Andrew McGregor
bingo! works like a charm
eqbridges
A: 

see here under 3.5.3(shell parameter expansion)

so in your case

${VARIABLE:−default}
ghostdog74
+1  A: 

Then there's the way of expressing your 'if' construct more tersely:

FOO='default'
[ -n "${VARIABLE}" ] && FOO=${VARIABLE}
Rob Wells
this is good for x-compatibility with earlier shells
eqbridges