Monday, 17 December 2018

Assigning default values to shell variables with a single command in bash



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?


Answer



Very close to what you posted, actually:



FOO=${VARIABLE:-default}  # If variable not set or null, use default.


Or, which will assign default to VARIABLE as well:



FOO=${VARIABLE:=default}  # If variable not set or null, set it to default.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...