Home > Net >  How to substitute variables in read with it's value?
How to substitute variables in read with it's value?

Time:02-08

Here's the code:

#!/bin/bash

read
dir =("$REPLY")

echo "${dir[@]}"
for i in "${dir[@]}"; do
        echo "$i"
done

My question is: how to substitute $some_variable in read with it's value?

CodePudding user response:

You can use variable indirection with parameter expansion/substitution to replace variable names with their values.

read
while [[ $REPLY =~ \$([a-z_A-Z][a-z_A-Z0-9]*) ]] ; do
    var=${BASH_REMATCH[1]}
    REPLY=${REPLY//\$$var/${!var}}
done
dir =("$REPLY")

Note that if the variable contains a name of another variable, it will be expanded as well, ad infitum. You might want to prevent that somehow.

CodePudding user response:

You don't want eval, because that would try to change more than the variables.
You can use envsubst:

REPLY='$HOME/a/$(date)'
dir =("$REPLY")

echo "Translating ${dir[@]}"
for i in "${dir[@]}"; do
  echo "Original code"
  echo "  $i"
  echo "Wrong code using crazy eval"
  eval echo "  ${i}"
  echo "When you have envsubst"
  echo "  ${i}" | envsubst
done

Result:

Translating $HOME/a/$(date)
Original code
  $HOME/a/$(date)
Wrong code using crazy eval
/home/username/a/Mon Feb 7 22:51:58 CET 2022
When you have envsubst
  /home/username/a/$(date)
  •  Tags:  
  • Related