tback tback - 6 months ago 10
Bash Question

Replace Environment Variable in argument to shell script

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

Answer

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"