Shell Script Tutorial

Variable

Let's look at some examples that show when to use each method of quoting.

USER="alan"

var1='Good Morning $USER !'
echo $var1

Result: Good Morning $USER !


var2="Good Morning $USER !"
echo $var2

Good Morning alan !

In the first case, the value of the 'var1' variable would probably not be what you wanted. The single quotation marks caused Bash to not treat $USER as a variable. In the second case, the results look much better. The double quotation marks allowed Bash to substitute the value of $USER, which is set automatically when you log in, in the string.

Here's another example that demonstrates a common error:

msg="Price is $5.00"
echo $msg

Actual result: Price is .00

We thought enough to quote the string, but the dollar sign tells Bash to use the value in the $5 variable, which is not what we wanted.. We can easily solve the problem by prefixing the dollar sign with a backslash, as shown here:

msg="Price is \$5.00"
echo $msg

Actual result: Price is $5.00


íP Single quotation marks, as in the preceding example, will always get you exactly what's inside the quotation marks--any characters that might otherwise have special meaning to the shell (like the dollar sign or the backslash) are treated literally.

íP Use double quotation marks when you want to assign a string that contains special characters the shell should act on.

íP The backslash is used to escape (treat literally) a single character (such as $ or *) that might otherwise be treated as a special character by the shell.


Server is hosted by Alanstudio
Linux Operating System

Recommend screen resolution 1024 x 768 / IE / FireFox
Alan Studio © 2007 by Alan Cheung Hin Lun. All rights reserved.