2

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?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
Deepak K M
  • 521
  • 1
  • 5
  • 13
  • 1
    @JohnSmith no that's different. op needs `path=\`bash -c "echo '$var4'"\`` or `path=\`eval echo $var4\`` – Jason Hu Jun 18 '15 at 14:57
  • 1
    Is the environment variable name fixed or does it vary — is it always `$IMP_FILES` or can it be `$HOME` and `$UMBRELLA` etc in other lines. – Jonathan Leffler Jun 18 '15 at 15:03
  • @JohnSmith Thanks, that thread helped. and thank you all for the help, I have decided to use eval it works good for me. – Deepak K M Jun 18 '15 at 15:39
  • @HuStmpHrrr `bash -c "echo '$var4'"` wont expand `$IMP_FILES` You need double quote around `$var4` and that makes it as insecure as eval. – Jahid Jun 18 '15 at 15:51

2 Answers2

0

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.

Jahid
  • 21,542
  • 10
  • 90
  • 108
0

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.

choroba
  • 231,213
  • 25
  • 204
  • 289