aloisdg
aloisdg

Reputation: 23541

Why bash cant find my variable from compgen into a loop?

I am trying to push some variables into a bash array. For some reasons I cant understand, my script find the variable templates_age directly but not in the loop.

You can try the code on BASH Shell Online.

script:

templates_age="42"
templates_name="foo"
echo "age=${templates_age}"
echo "name=${templates_name}"

readarray GREPPED < <($(compgen -A variable | grep "templates_"))
for item in "${GREPPED[@]}"
do
    echo "${item}"
done

output:

age=42
name=foo
./main.sh: line 32: templates_age: command not found

I tried different kind of echo "${item}" without success.

To convert from grep to array, I am using this logic.

Upvotes: 1

Views: 1012

Answers (2)

gniourf_gniourf
gniourf_gniourf

Reputation: 46903

I'm not sure why you want to use compgen and grep here. Wouldn't this be enough?

for item in "${!templates_@}"; do
    printf '%s=%s\n' "$item" "${!item}"
done

If you really want to populate an array, it's as simple as:

grepped=( "${!templates_@}" )

See Shell Parameter Expansion in the reference manual.

Upvotes: 3

anubhava
anubhava

Reputation: 786101

To correctly populate array from a command's output use process substitution without $(...) which is called command substitution:

readarray -t grepped < <(compgen -A variable | grep "templates_")

Also note use of -t to trim newlines.

Full script:

templates_age="42"
templates_name="foo"
echo "age=${templates_age}"
echo "name=${templates_name}"

readarray -t grepped < <(compgen -A variable | grep "templates_")
declare -p grepped

for item in "${grepped[@]}"
do
    printf "%s=%s\n" "${item}" "${!item}"
done

Upvotes: 1

Related Questions