0

Following this answer in superuser, I have wrote that function in bash:

_add_env()
{
    export $1
    if [[ ":\$$1:" != *":$2:"* ]]; then
            eval $1="\$$1:$2";
    fi
};  

I'm calling it that way: _merge_env PATH "/home/subway/land"

It seems that the condition is true even though PATH contains the given path.

Here is the relevant bash -x output:

  • 579 :[[ :$PATH: != :/\h\o\m\e/\s\u\b\w\a\y/\l\a\n\d: ]]
  • 580 :eval 'PATH=$PATH:/home/subway/land'

What am I doing wrong?

1 Answer 1

1

"\$$1" is not evaluated to the content of $PATH, but to $PATH. Use variable indirection:

[[ ":${!1}:" != *":$2:" ]]
Sign up to request clarification or add additional context in comments.

2 Comments

It works! Thanks. Would you mind to explain what does variable indirection mean? I mean, what exactly is its job?
Its jobs is what you try here: to use a value of a variable as a name of variable to expand.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.