Separating Variable Names from Surrounding Text

Problem

You need to print a variable along with other text. You are using the dollar sign in referring to the variable. But how do you distinguish the end of the variable name from other text that follows? For example, say you wanted to use a shell variable as part of a filename, as in:

for FN in 1 2 3 4 5
do
    somescript /tmp/rep$FNport.txt
done

How will the shell read that? It will think that the variable name starts with the $ and ends with the punctuation. In other words, it will think that $FNport is the variable name, not the intended $FN.

Solution

Use the full syntax for a variable reference, which includes not just the dollar sign, but also braces around the variable name:

somescript /tmp/rep${SUM}bay.txt

Discussion

Because shell variables are only alphanumeric characters, there are many instances where you won’t need to use the braces. Any whitespace or punctuation (except underscore) provides enough of a clue to where the variable name ends. But when in doubt, use the braces.

Get bash Cookbook 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.