Shell Scripting – Variables (Part 3)


Hello friends how are you doing today? Hope you are fine. In this article, we will be taking a look at part 3 of the variables, and how to use variables in shell scripting.  As we previously mention how you can use curly brackets around variable to avoid confusion:

echo $fooshine     # $fooshine is undefined
echo ${foo}shine   # displays the word "sunshine"

Also Read: Introduction to Shell Scripting

That’s not all, though – these fancy brackets have another, much more powerful use. We can deal with issues of variables being undefined or null (in the shell, there’s not much difference between undefined and null).

Using Default Values:

Let’s take a look at this snippet of code which asks for a user to provide some input, but also accepts defaults:

echo -en "What is your name [ `whoami` ] "
read myname
if [ -z "$myname" ]; then
echo "Your name is : $myname"

Passing the “-en” to echo tells it not to add a linebreak (for bash and csh). For Dash, Bourne and other compliant shells, you use a “\c” at the end of the line, instead. Ksh understands both forms.

This script runs like this if you accept the default by pressing “RETURN”:

osama$ ./
What is your name [ osama ]
Your name is : osama

… or, with user input:

osama$ ./
What is your name [ osama ] foo
Your name is : foo

This could be done better using a shell variable feature. By using curly braces and the special “:-” usage, you can specify a default value to use if the variable is unset:

echo -en "What is your name [ `whoami` ] "
read myname
echo "Your name is : ${myname:-`whoami`}"

This could be considered a special case – we’re using the output of the whoami command, which prints your login name (UID). The more canonical example is to use a fixed text, like this:

echo "Your name is : ${myname:-Hacker man}"

As with other use of the backticks, `whoami` runs in a subshell, so any cd commands, or setting any other variables, within the backticks, will not affect the currently-running shell.

Using and Setting Default Values

There is another syntax, “:=”, which sets the variable to the default if it is undefined:

echo "Your name is : ${myname:=Hacker man}"

This technique means that any subsequent access to the $myname the variable will always get a value, either entered by the user, or “Hacker man” otherwise.