Compound Strings

Most strings in Bourne shell are straight-forward. Using single-quotes causes the contents to be interpreted literally while using double-quotes allows string interpolation to occur and using no quotes adds word-splitting to the results.

Compound strings combine the features of unquoted, single-quoted, and double-quoted syntaxes to form a single string. You can seamlessly interchange styles without surrounding whitespace to construct a compound string.

For example, if you wanted to echo a sentence containing both double-quotes and single-quotes you can use a compound string:

1 #!/bin/sh
2 echo 'She asked, "Wie geht'\''s?"'
3 echo 'I answered, "C'"'est la vie.\""

The compound string on line 2 is actually the result of combining 3 separate strings. If we imagine space between these strings, we can more easily parse the compound string (working left-to-right):

String 1

String 2

String 3

Type

Single-quoted

Unquoted

Single-quoted

Contents

She asked, "Wie geht

\'

s?"

Interpolated?

No

Yes

No

Word Splitting?

No

Yes

No

Resulting String

She asked, "Wie geht

'

s?"

The compound string on line 3 is the combination of 2 separate strings:

String 1

String 2

Type

Single-quoted

Double-quoted

Contents

I answered, "C

'est la vie.\"

Interpolated?

No

Yes

Word Splitting?

No

No

Resulting String

I answered, "C

'est la vie"

The separate strings are combined without whitespace:

Below is a more complex example:

In the above excerpt we not only utilize a compound string on line 9 as the only argument to awk, but we use compound strings to escape user input when we need to evaluate arguments safely.

Running the above code:

Last updated

Was this helpful?