Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use string as variable name in BASH script

Tags:

bash

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.

like image 491
Andy Avatar asked Dec 08 '11 17:12

Andy


2 Answers

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.

like image 78
Michael Hoffman Avatar answered Oct 28 '22 10:10

Michael Hoffman


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

like image 27
soulmerge Avatar answered Oct 28 '22 09:10

soulmerge