Andy
Andy

Reputation: 8908

Use string as variable name in BASH script

I have the following:

#!/bin/sh

n=('fred' 'bob')

f='n'
echo ${${f}[@]}

and I need that bottom line after substitutions to execute

echo ${n[@]}

any way to do this? I just get

test.sh: line 8: ${${f}}: bad substitution

on my end.

Upvotes: 10

Views: 14452

Answers (2)

Michael Hoffman
Michael Hoffman

Reputation: 34324

You can do variable indirection with arrays like this:

subst="$f[@]"
echo "${!subst}"

As soulmerge notes, you shouldn't use #!/bin/sh for this. I use #!/usr/bin/env bash as my shebang, which should work regardless of where Bash is in your path.

Upvotes: 18

soulmerge
soulmerge

Reputation: 75704

You could eval the required line:

eval "echo \${${f}[@]}"

BTW: Your first line should be #!/bin/bash, you're using bash-specific stuff like arrays

Upvotes: 6

Related Questions