Variables

We described shell variables in Shell variables:

MYVAR=6echo $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 namels $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:

NAME="apple"echo "The plural of $NAME is $NAMEs"
The plural of apple is             Oops! No variable “NAMEs”echo  "The plural of $NAME is ${NAME}s"
The plural of apple is apples      What we wanted

Get Macintosh Terminal Pocket Guide now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.