Bad substitution in Bash

Advertisements

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

>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)]}"

Leave a ReplyCancel reply