bash variable indirection can't echo variable containing a function argument?

Viewed 74

I want to echo a variable containing a function argument, like this: echo ${str1_$1_str2}

The script is like this:

func_test () {
  eval str1_$1_str2=sucker
  echo ${str1_$1_str2}
}

func_test 1

When I execute the shell script, the error says:

${str1_$1_str2}: bad substitution

What is the problem?

1 Answers

Indirect parameter expansion might help:

func_test(){
  declare str1_$1_str2="foobar"
  local x="str1_${1}_str2"
  echo "${!x}"
}
func_test 222

Output:

foobar
Related