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?

2 Answers 2

9

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Useful to know: ${parameter-default} and ${parameter:-default} are almost equivalent. The extra : makes a difference only when parameter has been declared, but is null. tldp.org/LDP/abs/html/parameter-substitution.html
1

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

3 Comments

Since he mentions bash specifically, you should be using [[ over [
Why is [[ more appropriate than [ ?
@Elpezmuerto: You can find that on the bash wiki at FAQ #31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.