Setting default value for BASH variable


/ Published in: Bash
Save to your folder(s)

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


Copy this code and paste it in your HTML
  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

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.