Return to Snippet

Revision: 10735
at January 11, 2009 21:06 by jaduks


Initial Code
The syntax:

VARIABLE=${1:-DEFAULTVALUE} #set VARIABLE with the value of 1st Arg to the script,
                            #If 1st arg is not entered, set it to DEFAULTVALUE


#One simple bash script code:

...
tmpdir=/tmp
defvalue=1

DIR=${1:-$tmpdir} # Defaults to /tmp dir.
VALUE=${2:-$defvalue} # Default value is 1.

echo $DIR
echo $VALUE
..


Now while running the script, specify values for both the arguments.
$ ./defvaue.sh /dev 23
/dev
23

This time don't mention their values.
$ ./defvaue.sh
/tmp
1

so

DIR=${1:-$tmpdir}
VALUE=${2:-$defvalue}

is a replacement for the following:

[ -z $1 ] && DIR="/tmp"
[ -z $2 ] && VALUE=1

Initial URL
http://unstableme.blogspot.com/2007/12/setting-default-value-for-shell.html

Initial Description
To see how we can set default values for bash script variables inside bash script

Initial Title
Setting default value for BASH variable

Initial Tags
Bash

Initial Language
Bash