2

I've got a shell script that gets called with arguments that contain variable names. I want the variable to be replaced with their values. Consider the example below: It solves my problem, but it uses eval. I want to avoid eval for security reasons.

#!/bin/bash
#
# example:
# $> replace.sh arg '$VAR'
# arg value

VAR=value
ARGS=$(eval echo $*)

echo $ARGS
tback
  • 11,138
  • 7
  • 47
  • 71

2 Answers2

2

You are looking for indirect variable expansion:

$ SPY1=SPY2
$ SPY2="Lance Link"
$ SPY=${!SPY1}
$ echo $SPY
Lance Link
$ 
Gary_W
  • 9,933
  • 1
  • 22
  • 40
1

Works for me with something like:

#!/bin/bash
#
# example:
# $> replace.sh arg '$VAR'
# arg value

VAR=value
ARGS=""
for arg in "$@"
do
  arg="${arg/$/}" # remove preceding $ for indirect variable expansion to work
  ARGS="${ARGS} ${!arg}"
done

echo "$ARGS"
jayme
  • 1,241
  • 11
  • 24