How to do the expansion of variable in shell script?

338 views Asked by At

I hava a column in database which contains the following data:

sql_proc|test_sql.sql|/home/Desktop/myfile.txt|$IMP_FILES/myFolder|convert

I have fetched this into a variable and I have used the cut command with "|" as delimiter and saved each field in a different variable. Now let's consider VAR4 holds 4th field, i.e $IMP_FILES/myFolder. $IMP_FILES is an environment variable with value /home/OffFiles/Module.

How can I use VAR4 in order to get /home/OffFiles/Module/myFolder?

2

There are 2 answers

0
Jahid On BEST ANSWER

Using bash -c:

newvar="$(bash -c "echo $var")"

Using eval:

newvar="$(eval "echo $var")"

Example:

#!/bin/bash
var='$PATH'
echo "$var" #This will show that $var contains the string $PATH literally

#Using bash -c
newvar="$(bash -c "echo "$var"")"
echo "$newvar"

#using eval
newvar="$(eval "echo "$var"")"
echo "$newvar"

It will print the environment variable paths twice.

2
choroba On

The insecure solution is to use eval:

eval echo "$VAR4"

Don't do this, though, imagine what happens when VAR4='|rm -rf /'!

You can use associative array instead of environment variables.

#!/bin/bash
declare -A dict
dict[IMP_FILES]=/home/OffFiles/Module
# ...

VAR4='$IMP_FILES/myFolder'
while [[ $VAR4 =~ \$([_A-Z]+) ]] ; do
    key=${BASH_REMATCH[1]}
    VAR4=${VAR4/\$$key/${dict[$key]}}
done
echo "$VAR4"

Note that the solution is recursive, i.e. it can grow the string endlessly if the dictionary contains a key in a value. I'd drop shell and move to Perl, which can handle similar problems more easily.