I'm trying to write a bash function to init some environment variables. I want to append a path to them unless it is already there.
I'd call it like
$ add_to_path /home/brucewayne MYENV
This is what I have so far.
# adds $1 to path $2 (e.g. add '/opt/blabla' to $PYTHONPATH)
add_to_path() {
if [ -d "$1" ] && [[ ":${!2}:" != *":$1:"* ]]; then
$2="$1:${!2}"
fi
}
but when I run it, I get
./a.sh: line 6: MYENV=/home/brucewayne:/home/pal: No such file or directory
My guess is that $2="$1:${!2}" is not being interpreted as an assignment.
$2 should become MYENV and the value should be set to MYENV but, instead, it looks like I can't set the value by reference.
What would be a correct way of doing this in bash?