Skip to Main Content
Linux Pocket Guide
book

Linux Pocket Guide

by Daniel J. Barrett
February 2004
Beginner content levelBeginner
200 pages
5h 40m
English
O'Reilly Media, Inc.
Content preview from Linux Pocket Guide

Variables

We described variables earlier:

$ MYVAR=6
$ echo $MYVAR
6

All values held in variables are strings, but if they are numeric the shell will treat them as numbers when appropriate.

$ NUMBER="10"
$ expr $NUMBER + 5
15

When you refer to a variable’s value in a shell script, it’s a good idea to surround it with double quotes to prevent certain runtime errors. An undefined variable, or a variable with spaces in its value, will evaluate to something unexpected if not surrounded by quotes, causing your script to malfunction.

$ FILENAME="My Document"            Space in the name
$ ls $FILENAME                      Try to list it
ls: My: No such file or directory   Oops! ls saw 2 arguments
ls: Document: No such file or directory
$ ls -l "$FILENAME"                  List it properly
My Document                          ls saw only 1 argument

If a variable name is evaluated adjacent to another string, surround it with curly braces to prevent unexpected behavior:

$ HAT="fedora"
$ echo "The plural of $HAT is $HATs"
The plural of fedora is             Oops! No variable "HATs"
$ echo  "The plural of $HAT is ${HAT}s"
The plural of fedora is fedoras     What we wanted
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 Pocket Guide, 2nd Edition

Linux Pocket Guide, 2nd Edition

Daniel J. Barrett
Linux in a Nutshell, 6th Edition

Linux in a Nutshell, 6th Edition

Ellen Siever, Stephen Figgins, Robert Love, Arnold Robbins

Publisher Resources

ISBN: 9780596806347Errata Page