O'Reilly logo

Linux Pocket Guide, 2nd Edition by Daniel J. Barrett

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

Variables

We described shell 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

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