Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic bash: set default value for variable [duplicate]

Tags:

idioms

bash

How can I set a default value for a bash variable in a concise, idiomatic way? This just looks ugly:

if [[ ! -z "$1" ]]; then
    option="$1"
else
    option="default"
fi
like image 924
slezica Avatar asked Jul 31 '26 13:07

slezica


2 Answers

default value               : ${parameter:-word} \
assign default value        : ${parameter:=word}  |_ / if unset or null -
error if empty/unset        : ${parameter:?mesg}  |  \ use no ":" for unset only
use word unless empty/unset : ${parameter:+word} /
like image 113
bobah Avatar answered Aug 02 '26 03:08

bobah


You can use:

option=${1:-default}

This sets option to the first command line parameter if a first command line parameter was given and not null. Otherwise, it sets option to default. See Bash reference manual for the details on parameter expansion and some useful variants of this form.

like image 29
Toxaris Avatar answered Aug 02 '26 05:08

Toxaris



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!