Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Bad substitution in Bash

I have written this code in which m getting bad substitution error. Please help here.

#!/bin/bash

function detect_value(){

    #some operation gives u a value
    echo "ABCD"

}

ABCD_COUNT=26

echo "${"$(detect_value)"_COUNT}"

bash run.sh
run.sh: line 12: ${"$(detect_value)"_COUNT}: bad substitution

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The name of a parameter has to be static, not produced by another expression. To do what you want, you need to use indirect parameter expansion, where the name of the parameter to expand is stored in another parameter.

t=$(detect_value)_COUNT
echo ${!t}

Depending on your use case, you might want to use an associative array instead.

declare -A counts

counts[ABCD]=26

detect_value () {
    echo ABCD
}

echo "${counts[$(detect_value)]}"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading