February 2004
Beginner
200 pages
5h 40m
English
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