Use Double Quotes to Resolve Variables in Strings with Embedded Spaces

If a string contains embedded spaces, you can enclose the string in double quotes (") so that the shell interprets the whole string as one entity instead of more than one.

For example, if you assigned the value of abc def (abc followed by one space, followed by def) to a variable called x in a shell program as follows, you would get an error because the shell would try to execute def as a separate command:

Command x=abc def set x=abc def

Environment pdksh and bash tcsh

The shell will execute the string as a single command follows:

Command Environment x="abc def" pdksh and bash set x="abc tcsh def"

if you surround the string in double quotes as

The double quotes resolve all variables within the string. Here is an example for pdksh and bash:

var="test string" newvar="Value of var is $var" echo $newvar

Here is the same example for tcsh:

set var="test string"

set newvar="Value of var is $var"

echo $newvar

If you execute a shell program containing the preceding three lines, you get the following result:

Value of var is test string

Was this article helpful?

0 0

Post a comment