LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Variable expansion in BASH (https://www.linuxquestions.org/questions/programming-9/variable-expansion-in-bash-602163/)

champak 11-24-2007 09:43 PM

Variable expansion in BASH
 
Hi..

Im reading values from a file line by line.
Sample File
..
first|blah
second|$some_shell_var
...

I have to process these values like
...
source=$(echo $line | cut -d'|' -f1)
dest=$(echo $line | cut -d'|' -f2)

echo $source
echo $dest
...

When I echo the values I get 'blah' for the first line(first|blah).
For the second line I get '$some_shell_var'. But instead I want the variable value to be expanded(I mean I want the $some_shell_var to be substituted with its value). How this can be done in BASH?

Any ideas?

Thanks

ntubski 11-24-2007 11:11 PM

Code:


#check if dest starts with a '$'
if [ ${dest:0:1} = '$' ] ; then
  #remove the '$'
  dest="${dest:1}"
  #{!dest} uses indirection,
  #search for variable indirection in the bash man page for details
 
  echo "source = $source, dest = ${!dest}"
else
  echo "source = $source, dest = $dest"
fi


champak 11-24-2007 11:36 PM

Thanks for a lot ntubski.
But just checking if there's any direct approach to get the variable expanded without removing the '$' char

ntubski 11-25-2007 12:36 PM

I guess you could use eval:

Code:

eval "echo dest = ${dest}"
But if you have something in your file like
Code:

second|$(rm -rf /*)
bad things could happen...

champak 11-26-2007 01:19 AM

ya thx again

bigearsbilly 11-26-2007 03:44 AM

try this,
Code:



IFS=\|
while read f1 f2; do
    eval source="$f1"
    eval dest="$f2"
done



All times are GMT -5. The time now is 09:33 AM.