Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell script variable reflection [duplicate]

Tags:

bash

shell

I am writing a shell script (#!/bin/sh) which has a variable VAR which contains the name of another variable FOO, which in turn is set to BAR.

FOO=BAR
VAR=FOO

I want to get the value of the variable named in VAR, so something like:

echo "${$VAR}"

But that does not seem to work. Suggestions?

like image 541
user3739584 Avatar asked Jun 16 '14 16:06

user3739584


1 Answers

In Bash:

echo "${!VAR}"

Without Bash (though it works in Bash too):

eval echo "\${$VAR}"

Beware: eval is a very general mechanism that can run you into problems very easily. It works fine here, but be cautious about using it more generally.

like image 194
Jonathan Leffler Avatar answered Sep 30 '22 18:09

Jonathan Leffler