June 2012
Beginner
227 pages
5h 43m
English
We described shell variables in Shell variables:
➜MYVAR=6➜echo $MYVAR6
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 + 515
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 $FILENAMETry 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
Read now
Unlock full access