Variable default values in Bash

Posted: 2nd October 2011 by Tim in Bash
Tags: , , , , , , ,

Sometimes you will be writing a script which, for example, can have some configuration changed from a command line argument. In traditional programming languages you would declare your variables with default values and then overwrite those values with the arguments which are passed in. In bash, however, you can do this all in one statement.

Lets say you want to write a program which prints a hello message using a person’s name. By default the program will use the user’s username in the message or, if an argument is supplied, that argument will be used instead. This could be written like so:

#!/bin/bash
name=${1:-$(whoami)}
echo "Hello, $name!"
exit

If you are logged in as “tim” and run the program with no arguments, it will print Hello, tim!. Otherwise, if you run it as ./name.sh Max then it will print Hello, Max!. Simple