Skip to content
Advertisement

Getting bad substitution error in shell script

I have a variable COUNTRY=”INDIA”

and another sets of variables:- INDIA_POPULATION=”5,00,00,000″, CHINA_POPULATION=”6,00,00,000″.

In script I am trying to call them using command:-

echo ${ ${COUNTRY}_POPULATION }

But I am getting bad substitutionenter image description here error. Can someone please tell how to solve it ??

Advertisement

Answer

You misplaced a bracket: {$COUNTRY}_POPULATION should be ${COUNTRY}_POPULATION. But even then it would not work as you expect. Use bash indirect expansion:

$ name="${COUNTRY}_POPULATION"
$ echo "${!name}"
5,00,00,000

Or, if you have bash version >= 4.3, you can also use a refname:

$ declare -n name="${COUNTRY}_POPULATION"
$ echo "$name"
5,00,00,000
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement