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
2

2 Answers 2

2

You are looking for indirect variable expansion:

$ SPY1=SPY2
$ SPY2="Lance Link"
$ SPY=${!SPY1}
$ echo $SPY
Lance Link
$ 
Sign up to request clarification or add additional context in comments.

Comments

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.