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 should follow me on twitter here or grab rss feed to keep track of new changes.
Featured Articles:
- 30 Handy Bash Shell Aliases For Linux / Unix / Mac OS X
- Top 30 Nmap Command Examples For Sys/Network Admins
- 25 PHP Security Best Practices For Sys Admins
- 20 Linux System Monitoring Tools Every SysAdmin Should Know
- 20 Linux Server Hardening Security Tips
- Linux: 20 Iptables Examples For New SysAdmins
- Top 20 OpenSSH Server Best Security Practices
- Top 20 Nginx WebServer Best Security Practices
- 20 Examples: Make Sure Unix / Linux Configuration Files Are Free From Syntax Errors
- 15 Greatest Open Source Terminal Applications Of 2012

- My 10 UNIX Command Line Mistakes
- Top 10 Open Source Web-Based Project Management Software
- Top 5 Email Client For Linux, Mac OS X, and Windows Users
- The Novice Guide To Buying A Linux Laptop













{ 3 comments… read them below or add one }
Thanks for the explanation… I’ve been trying to work with some shell scripts which are a bit more advanced then what i’m used to and this helped a lot. I was wondering if you also knew what ${VAR:+xxx} syntax and/or the ${VAR:-xxx} is for?
I’m seeing this in a script which uses
export ${NO_EXPORT:+-n} CONFIG_SECTION=”$name”
is this just a method of applying an conditional flag to a variable inline (like an assert statement)? I’m not sure as if that were true they could just as simply do
[ -n "$NO_EXPORT" ] && CONFIG_SECTION=”$name”
See this FAQ.
http://tldp.org/LDP/abs/html/parameter-substitution.html