LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   bash variable substitution (https://www.linuxquestions.org/questions/programming-9/bash-variable-substitution-804899/)

Jerry Mcguire 04-29-2010 03:01 AM

bash variable substitution
 
I have a config file (not a script) that states where to find a file named key.dat. With this config, I need to operate on the key.dat, so I did the following...

Code:

$ cat myconfig
keyfile=$mypath/key.dat

$ touch $mypath/key.dat # mypath is of course defined

$ KEYFILE=`grep '^keyfile=' myconfig | cut -d '=' -f 2`

$ echo $KEYFILE
$mypath/key.dat

$ [ -f $KEYFILE ] || echo 'Not Found'
Not Found

Since '$mypath' is not expanded in the test, the key.dat is not found.

My question is, how can I make $mypath expanded in the test so that I can get hold of the file key.dat?

Thanks.

evo2 04-29-2010 03:06 AM

I think you don't need to mess around with grep. Just source the file. What is the output of the following?
Code:

. myconfig
echo $keyfile

Evo2.

PS. You say that myconfig is not a script, but from what you post above the syntax is bourne shell compatible, so sourcing it should work.

Jerry Mcguire 04-29-2010 03:14 AM

Can't. The file is not executable. e.g. 664

and there are other stuff in the file that is not valid command.

gnashley 04-29-2010 03:28 AM

A file doesn't have to be executable in order to source it. Try the suggestion.

Jerry Mcguire 04-29-2010 03:35 AM

Right. That is true. Thank you both.

For the sake of learning, if sourcing the file doesn't work, e.g. myconfig does not contain valid bash syntax. Any work around to expand 'variable inside strings'?

colucix 04-29-2010 04:26 AM

Quote:

Originally Posted by Jerry Mcguire (Post 3951519)
My question is, how can I make $mypath expanded in the test so that I can get hold of the file key.dat?

The eval built-in may serve to force shell expansions. For example:
Code:

$ echo $mypath
/usr/local
$ eval $(grep '^keyfile=' myconfig)
$ echo $keyfile
/usr/local/key.dat


Jerry Mcguire 04-29-2010 09:33 AM

Thanks. This is what I needed.

Code:

$ KEYF=`eval echo $(grep '^keyfile=' myconfig | cut -d '=' -f 2)`

$ [ -f $KEYF ] && echo 'Found'
Found



All times are GMT -5. The time now is 06:42 PM.