Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

shell

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?

like image 399
Edward Q. Bridges Avatar asked Jan 06 '10 14:01

Edward Q. Bridges


People also ask

How do you assign a value to a variable in shell?

Shell provides a way to mark variables as read-only by using the read-only command. After a variable is marked read-only, its value cannot be changed. /bin/sh: NAME: This variable is read only.

How do I set an environment variable for a single command?

We can set variables for a single command using this syntax: VAR1=VALUE1 VAR2=VALUE2 ... Command ARG1 ARG2...


1 Answers

Very close to what you posted, actually. You can use something called Bash parameter expansion to accomplish this.

To get the assigned value, or default if it's missing:

FOO="${VARIABLE:-default}"  # If variable not set or null, use default. # If VARIABLE was unset or null, it still is after this (no assignment done). 

Or to assign default to VARIABLE at the same time:

FOO="${VARIABLE:=default}"  # If variable not set or null, set it to default. 
like image 156
Andrew McGregor Avatar answered Sep 22 '22 06:09

Andrew McGregor