ajwood
ajwood

Reputation: 19027

bash: expanding variable

I'm trying to add a function to my .bashrc to ease prepending $PWD to environment variables. I'd like the function to take one argument -- the name of the variable on which to prepend the working directory. I'm thinking something like this...

function prependTo{ export $1=$PWD:\$$1 }

Is what I'm looking to do possible in bash?

Upvotes: 1

Views: 671

Answers (1)

SiegeX
SiegeX

Reputation: 140327

Don't use the function keyword, it is deprecated and non-POSIX. Instead do this:

 prependTo(){ export $1=$PWD:${!1}; }

Explanation

From man bash

If the first character of parameter is an exclamation point, a level of variable indirection is introduced. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion.

Upvotes: 3

Related Questions