Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default user variable in bash scripting

Tags:

bash

shell

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?

like image 262
Elpezmuerto Avatar asked Aug 01 '26 20:08

Elpezmuerto


1 Answers

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.

like image 192
Daenyth Avatar answered Aug 04 '26 15:08

Daenyth



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!