O'Reilly logo

Shell Scripting: Expert Recipes for Linux, Bash, and More by Steve Parker

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Providing Default Values

Often, you need to have a variable contain a value, but you don’t know whether or not it is currently set. It can be useful to define a default value if the variable in question is not set.

If you write a script that requires the user to edit a file, you could do this:

echo "You must now edit the file $myfile"
sleep 5
vi "${myfile}"
echo "Thank you for editing $myfile"

But not everybody likes vi. They might want to use emacs, or nano, or gedit, or kate, or anything else.

One way to do this is to allow the user to set a variable (by convention this is called EDITOR) to define their favorite editor. The following:

vi "${myfile}"

becomes:

${EDITOR} "${myfile}"

which solves the problem nicely; the user defines whatever he or she wants in EDITOR, and the script is much more flexible. But what if EDITOR is not set? Because variables do not need to be declared, no error will occur; $EDITOR will just silently be replaced with the empty string:

 "${myfile}"

If $myfile is /etc/hosts, then the system will try to execute /etc/hosts, which will fail, because /etc/hosts doesn’t (or at least, it shouldn’t!) have the executable bit set:

ls -l /etc/hosts
-rw-r--r-- 1 root root 1494 2008-05-22 00:44 /etc/hosts

If $myfile is “rm -rf /” then it will be executed, not edited, which is far from the intended action. To avoid this, supply a default value for the variable. The syntax for this is ${parameter:-word}. The curly brackets are required, and word ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required