14

Is it possible, or is there some elegant hack to do indirect variable expansion in POSIX as can be done in Bash?

For context, I'm trying to do the following:

for key in ${!map_*}
do
    # do something
done

EDIT: To clarify, I'd like to access shell variables that begin with map_.

4
  • 5
    Voted to reopen. The Q wants to know how to get indirectly, all the variables that match the wildcard (map_*).
    – slm
    Commented Jan 30, 2014 at 16:45
  • I was surprised I was unclear with regards to my question :P
    – Dashed
    Commented Jan 31, 2014 at 21:51
  • 4
    Please re-open. It's a case of sh VS bash -- see stackoverflow.com/a/5725402/1172302. Commented Dec 22, 2015 at 3:19
  • 1
    So this is why some folks don't like stackoverflow and some stackexchange sites.
    – Dashed
    Commented Apr 15, 2016 at 18:44

1 Answer 1

7

The hack is to use eval:

aaa=1
aab=2
aac=3

eval_like() {
    pattern=$1
    vars=`set |grep "^$pattern.*=" | cut -f 1 -d '='`
    for v in $vars; do
        eval vval="\$$v"
        echo $vval
    done
}   

for i in `eval_like aa`; do
    echo $i
done
2
  • Thanks! set was what I was looking for.
    – Dashed
    Commented Jan 30, 2014 at 16:31
  • 1
    That's not foolproof though and is an arbitrary command injection vulnerability (like when it's run in an environment that has QUERYSTRING=$'\nmap_$(reboot)=x'). Also beware that the bash shell includes the list of functions in the output of set (when not running as sh). Commented Aug 1, 2019 at 12:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .