1

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?

1 Answer 1

2

Add export in your function:

add_to_path() {
    if [ -d "$1" ] && [[ ":${!2}:" != *":$1:"* ]]; then
       export $2="$1:${!2}"
    fi
}
Sign up to request clarification or add additional context in comments.

2 Comments

damn it I had tried that but with a different right side and failed. thanks! it does work
You can make it a bit cleaner by using: [[ -d "$1" && ":${!2}:" != ":$1:" ]] && export $2="$1:${!2}". The if .. then .. fi construct would no longer be needed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.