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
doneHow 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.txtDiscussion
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.
See Also
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access