BASH shell scripting tip: Set default values for variable
A shell variable may be assigned to by a statement using following syntax:
var=value
If value is not given, the variable is assigned the null string. In shell program it is quite useful to provide default value for variables. For example consider rsync.sh script:
#!/bin/bash
RSRC=$1
LOCAL=$2
rsync -avz -e 'ssh ' user@myserver:$RSRC $LOCAL
This script can be run as follows:
$ ./rsync.sh /var/www .
$ ./rsync.sh /home/vivek /home/vivek
It will sync remote /home/vivek directory with local /home/vivek directory. But if you need to supply default values for a variable you can write as follows:
#!/bin/bash
RSRC=$1
LOCAL=$2
: ${RSRC:="/var/www"}
: ${LOCAL:="/disk2/backup/remote/hot"}
rsync -avz -e 'ssh ' user@myserver:$RSRC $LOCAL
: ${RSRC:="/var/www"} ==> this means if the variable RSRC is not already set, set the variable to /var/www. You can also write same statement with following code:
if [ -z "$RSRC" ] then RSRC="/var/www" fi
You can also execute a command and set the value to returned value (output). For example if the variable NOW is not already set, execute command date and set the variable to the todays date using date +"%m-%d-%Y":
#!/bin/bash
NOW=$1
....
.....
: ${NOW:=$(date +"%m-%d-%Y")}
....
..
You may also be interested in other helpful articles:
- nixCraft FAQ roundup
- Solaris adding new user accounts
- nixCraft FAQ Roundup
- Using Color Effectively At a Shell Prompt / Console
- How to tune MySQL server for performance
Leave a Reply
We encourage your comments, and suggestions. But please stay on topic, be polite, and avoid spam. Thank you very much for stopping by our site!
Tags: default values, fi, null string, rsync, shell program, shell set variable value, shell variable, ssh, sync, syntax, todays date, variables



Recent Comments
Today ~ 13 Comments
Today ~ 50 Comments
Today ~ 14 Comments
Today ~ 5 Comments
Yesterday ~ 22 Comments