0

How can I add in bash a test checking if a given directory (say /usr/local/bin) is already in a variable, say $PATH, before actually doing it?

Context: I am creating a script for a package I maintain for which I wish to include all steps to install dependencies. This involves changing the $PATH variable, but my question is more general (changes involve also $PYTHONPATH for instance). However, I wish also to not mingle with the existing variables and to not prepend it if it already exists.

2
  • if you look at the answers for the possible duplicate, you will see that these are quite different (detecting versus adding once). looks quite unproductive with respect to the community to downvote the question just for that. Commented Nov 19, 2014 at 14:29
  • Your question is about detecting, not about adding. I marked your question as duplicate, but didn't downvote it. Commented Nov 19, 2014 at 14:34

2 Answers 2

2

Using grep you can test

echo "$PATH" | grep -o '/usr/local/bin'

Example:

var=$(echo $PATH | grep -o  '/usr/local/bin')
if [ -n "$var" ] ; then
    echo 'already Existe' 
else
    echo 'Not exists' 
fi

Output:

already Existe
Sign up to request clarification or add additional context in comments.

2 Comments

thanks for your answer. it perfectly fits to my need !
ah the joy of coming back to an answer to a question asked nine years ago!
0

You can check like this:

export p='/usr/local/bin'
(IFS=: a=("$PATH"); printf "%s\n" "${a[@]}"|grep -xq "$p") && echo "exists" || echo "nope"
exists

export p='/usr/local/bin123'
(IFS=: a=("$PATH"); printf "%s\n" "${a[@]}"|grep -xq "$p") && echo "exists" || echo "nope"
nope

grep options used:

  • -x -> exact match
  • -q -> quiet, just returns exit status

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.