tags:

views:

39

answers:

2

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?

A: 

Try eval:

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

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

Bart Sas
You need spaces and a semicolon: `function prepend() { eval "$1=$2:\$$1"; }`. Be aware of the [security implications of `eval`](http://mywiki.wooledge.org/BashFAQ/048).
Dennis Williamson
A: 

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"
}
camh