1

I started this question by looking at Add directory to $PATH if it's not already there. In my case, I wanted to do the same to LD_LIBRARY_PATH also. How to do that without writing a script for every variable?

2 Answers 2

1

Given a variation on pathmunge in /etc/profile

munge () {
    if [[ ":${!1}:" != *:"$2":* ]]; then
        if [[ $3 == after ]]; then
            declare -g $1="${!1}:$2"
        else
            declare -g $1="$2:${!1}"
        fi
    fi
}

We can do:

$ A=a
$ munge A b after
$ echo $A
a:b
$ munge A c before
$ echo $A
c:a:b
$ munge A a before
$ echo $A
c:a:b
1

According to this article, http://www.linuxjournal.com/content/return-values-bash-functions, it is possible to modify an outside variable, given its name, like this:

function myfunc()
{
    local  __resultvar=$1
    local  myresult='some value'
    eval $__resultvar="'$myresult'"
}

myfunc result
echo $result

Now, using this script and the original question, I've wrote two functions, one to add before current value and one to add after:

function add_directory_before()
{
    local VAR=$1
    local VALUE=$(eval echo \$${VAR})
    if [ -d $2 ] && [[ ":$VALUE:" != *":$2:"* ]] ; then
        eval $VAR=$2:$VALUE
    fi
}

function add_directory_after()
{
    local VAR=$1
    local VALUE=$(eval echo \$${VAR})
    if [ -d $2 ] && [[ ":$VALUE:" != *":$2:"* ]] ; then
        eval $VAR=$2:$VALUE
    fi
}

and the usage:

add_directory_after LD_LIBRARY_PATH /usr/local/lib64

or

add_directory_before PATH $HOME/bin
2
  • With bash, don't need eval: local value="${!1}" -- that's "variable indirection", see gnu.org/software/bash/manual/… Dec 11, 2014 at 15:25
  • Also, get out of the habit of using ALLCAPSVARS. Leave those for the shell. One day you'll accidentally write PATH=foo and then wonder why your script is broken Dec 11, 2014 at 15:26

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .