Skip to Content
Shell Scripting: Expert Recipes for Linux, Bash, and More
book

Shell Scripting: Expert Recipes for Linux, Bash, and More

by Steve Parker
August 2011
Beginner to intermediate
600 pages
14h 29m
English
Wrox
Content preview from Shell Scripting: Expert Recipes for Linux, Bash, and More

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Linux Command Line and Shell Scripting Techniques

Linux Command Line and Shell Scripting Techniques

Vedran Dakic, Jasmin Redzepagic
Linux Shell Scripting Cookbook - Third Edition

Linux Shell Scripting Cookbook - Third Edition

Clif Flynt, Sarath Lakshman, Shantanu Tushar

Publisher Resources

ISBN: 9781118166321Purchase bookDownloads