-   Programming (
-   -   BASH string expansions (

Barbarian 11-21-2001 01:35 AM

BASH string expansions
I'm a bit of a newbie to Linux and BASH and I've been BASHing my head again my monitor with a problem with string expansions. Perhaps one of you clever types can help me out....

To cut a long story short I'm 'grepping' a configuration file and extracting a number of file paths to be used for populating new project accounts. From the read string I want to expand any shell variable (such as $HOME) before using the expanded string in a 'cpy' or 'cvs' command e.g:-

When a parse and (attempt to) expand my string I always end up with the unexpanded variable still in the string. I've tried the various '${}' operators, but either I'm doing it wrong or they only seem to work on variables created within the shell.

Any help would be most appreciated.

crabboy 11-21-2001 10:06 AM

The $HOME variables that the shell reads as a string is treated as any other string to the shell. What you need to do is read in the $HOME and use sed to substitute the $HOME read with the shell $HOME variable. It gets kind of tricky since sed uses the '/' character as its delimeter and the paths also contain '/'s. What I had to do is create a new home variable that has the '/'s escaped out, this I can pass to sed.



ESCHOME=`echo $HOME | sed 's/\//\\\\\//g'`

read VAR
echo $VAR | sed "s/\$HOME/${ESCHOME}/"

Barbarian 11-21-2001 10:40 PM

Thanks for that, it's an interesting idea and I'll have to add 'sed' to my many things to learn about Linux!

Unfortunately, it doesn't quite give me the result I wanted and after re-reading my initial post (and cursing at my English errors) I decided I wasn't clear enough.

Your solution has a hardcoded $HOME in the string (perhaps $HOME was a bad example), however, the string I've just extracted and stored in a variable contains (say):-


where DIRVAR has been setup globally. Basically, the DIRVAR would contain another directory path which would be used as some sort of system release i.e "beta_release/1a" or "/issue_release/2a" etc...

I've passed the read in string to a subroutine. If I then 'echo' $1 from within my bash script, that is exactly what I get (without $DIRVAR expanded). However, if I build my string manually from the command line it is displayed correctly.
It is easy to parse out the directory path and detect the '$' to denote a variable for expansion. However, I'm not sure whether I'd end up still being in the same boat. Any ideas now?

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