Benjamin Schieder

[SOLUTIONS] FIXING YOUR VARIABLES

2006 February 14

In bash, you can call variables in two ways:

${variable}
$variable

The first is better for a number of reasons:
First: Variable operations
There are several operations you can do on a variable, each one requiring the curly brackets:
Remove string at the end of the variable:
var="123ABC"
var=${var%ABC}
echo ${var}
123

Remove string at the beginning of the variable:
var="123ABC"
var=${var#123}
echo ${var}
ABC

Replace part of the variable:
var="123ABC"
var=${var/3A/A3}
echo ${var}
12A3BC


So it is at least a good habit to have a clean look in your script.

Second: String operations
Assume the following scenario: You have a variable 'var' that contains a string that you want to suffix with another string. Example:
var="ABC"
echo "$varDEF"

This will not work because 'varDEF' is also a variable.
echo "${var}DEF"

This will work because you explicitly reference the variable 'var'.

Now, if you already have a bunch of scripts that use the '$var' style and want to transform them into '${var}' style, doing it manually is a tedious job.
For vim users, I have this solution:
:%s/$([A-Za-z0-9_@$]+)/${1}/g

This regular expression will wrap all variables in curly brackets.

EOF

Category: blog

Tags: Solutions