views:

41

answers:

2

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
+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
Since he mentions bash specifically, you should be using `[[` over `[`
Daenyth
Thanks, fixed it
iniju
Why is `[[` more appropriate than `[` ?
Elpezmuerto
@Elpezmuerto: You can find that on the bash wiki at [FAQ #31](http://mywiki.wooledge.org/BashFAQ/031)
Daenyth