Posted By

jaduks on 01/11/09


Tagged

Shell Bash


Versions (?)

Who likes this?

1 person have marked this snippet as a favorite

scilec


Setting default value for BASH variable


 / Published in: Bash
 

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

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

  1. The syntax:
  2.  
  3. VARIABLE=${1:-DEFAULTVALUE} #set VARIABLE with the value of 1st Arg to the script,
  4. #If 1st arg is not entered, set it to DEFAULTVALUE
  5.  
  6.  
  7. #One simple bash script code:
  8.  
  9. ...
  10. tmpdir=/tmp
  11. defvalue=1
  12.  
  13. DIR=${1:-$tmpdir} # Defaults to /tmp dir.
  14. VALUE=${2:-$defvalue} # Default value is 1.
  15.  
  16. echo $DIR
  17. echo $VALUE
  18. ..
  19.  
  20.  
  21. Now while running the script, specify values for both the arguments.
  22. $ ./defvaue.sh /dev 23
  23. /dev
  24. 23
  25.  
  26. This time don't mention their values.
  27. $ ./defvaue.sh
  28. /tmp
  29. 1
  30.  
  31. so
  32.  
  33. DIR=${1:-$tmpdir}
  34. VALUE=${2:-$defvalue}
  35.  
  36. is a replacement for the following:
  37.  
  38. [ -z $1 ] && DIR="/tmp"
  39. [ -z $2 ] && VALUE=1

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: deepsoul on July 26, 2009

When the value is not to be assigned to a new variable, this can be abbreviated to:

: ${var:=$default}

: does nothing but evaluate its argument, which assigns the $default to $var if it is unset.

You need to login to post a comment.