
Escaping variable names inside other variables in Bash scripts
If you have a variable that comprises of another variable like so and try the following:
var_name=test
var_name_full=$var_name_and_extension
This won’t work because Bashwill interpret the underscore after $var_name
as part of the variable name and look for a variable called $var_name_and_extension
and not find it.
There are two ways to make this work:
- Enclose the variable name in curly braces as follows:
var_name=test
var_name_full=${var_name}_and_extension
2. Use double quotes to delineate between the variable name and the string:
var_name=test
var_name_full=$var_name"_and_extension"