BASH shell scripting tip: Set default values for variable

A shell variable may be assigned to by a statement using following syntax:


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 script:
rsync -avz -e ‘ssh ‘ user@myserver:$RSRC $LOCAL

This script can be run as follows:
$ ./ /var/www .
$ ./ /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:

: ${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" ]

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”:

: ${NOW:=$(date +"%m-%d-%Y")}
🐧 Get the latest tutorials on SysAdmin, Linux/Unix, Open Source & DevOps topics via:
CategoryList of Unix and Linux commands
File Managementcat
FirewallCentOS 8 OpenSUSE RHEL 8 Ubuntu 16.04 Ubuntu 18.04 Ubuntu 20.04
Network Utilitiesdig host ip nmap
OpenVPNCentOS 7 CentOS 8 Debian 10 Debian 8/9 Ubuntu 18.04 Ubuntu 20.04
Package Managerapk apt
Processes Managementbg chroot cron disown fg jobs killall kill pidof pstree pwdx time
Searchinggrep whereis which
User Informationgroups id lastcomm last lid/libuser-lid logname members users whoami who w
WireGuard VPNCentOS 8 Debian 10 Firewall Ubuntu 20.04

4 comments… add one
  • 0xception Aug 7, 2009 @ 23:23

    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”

  • kate Aug 1, 2012 @ 19:18
  • David Apr 1, 2014 @ 19:05

    You can even write it neater by using “:-” like in


Leave a Reply

Your email address will not be published. Required fields are marked *

Use HTML <pre>...</pre>, <code>...</code> and <kbd>...</kbd> for code samples.