Ashish Agarwal
Ashish Agarwal

Reputation: 3030

Can you specify which environment variable to modify as argument to function in Bash?

I have written the following two functions in Bash:

function prepend_path() { PATH=$1:$PATH }
function prepend_manpath() { MANPATH=$1:$MANPATH }

The bodies of the functions are actually going to be more complicated. To avoid code duplication, I would like to do something like the following:

function prepend() { "$1"=$2:"$1" }
function prepend_path() { prepend PATH $1 }
function prepend_manpath() { prepend MANPATH $1 }

However, prepend is not valid Bash. The idea is to pass the name of an environment variable as an argument to Bash. Is it possible, or is there another solution?

Upvotes: 2

Views: 266

Answers (2)

Bart Sas
Bart Sas

Reputation: 1645

Try eval:

function prepend() { eval "$1=$2:\$$1"; }

eval will evaluate its argument as if it is a command.

Upvotes: 1

camh
camh

Reputation: 42528

Here are some functions I have in my shell library for exactly this task. It also takes care of when the environment variable is empty so as to not add a colon in that case.

append_path()
{
  eval $1=\${$1:+\$$1\\:}$2
}

prepend_path()
{
  eval $1=$2\${$1:+\\:\$$1}
}

And here's how I use it

append_binpath()
{
  append_path PATH "$1"
}

append_manpath()
{
  append_path MANPATH "$1"
}

Upvotes: 1

Related Questions