I am writing a bash shell script, run where the user is expected to pass a path into it as the $1 variable. How can I determine if $1 is missing and define a default value instead for it?
+7
A:
You can check the length of the variable.
if [[ -z $1 ]]; then
echo '$1 is zero-length. Please provide a value!'
fi
If you just want to use a default value, you can use a brace expansion.
first_param=${1:-defaultvalue}
The ${varname:-foo}
construct will use the value of varname
if it is set, or use what follows the :-
if it is not set.
Daenyth
2010-09-28 16:33:54
+1
A:
Do you mean detect if a value is missing, or if the directories in the path are missing? For the former:
MYPATH=$1
if [[ -z $MYPATH ]]
then
MYPATH=$MYDEFAULTPATH
fi
for the latter:
MYPATH=$1
if [[ ! -d $MYPATH ]]
then
MYPATH=$MYDEFAULTPATH
fi
iniju
2010-09-28 16:36:30
Since he mentions bash specifically, you should be using `[[` over `[`
Daenyth
2010-09-28 16:40:43
Thanks, fixed it
iniju
2010-09-28 16:48:49
Why is `[[` more appropriate than `[` ?
Elpezmuerto
2010-09-28 16:58:38
@Elpezmuerto: You can find that on the bash wiki at [FAQ #31](http://mywiki.wooledge.org/BashFAQ/031)
Daenyth
2010-09-28 17:09:59