Image for post
Image for post

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:

  1. 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"

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store