I have a file which is sourced by an application, adding relevant directories to $PATH and $LD_LIBRARY_PATH.

This is fine, but it results in somewhat excessive pollution of the $PATH and $LD_LIBRARY_PATH, since quite a few paths are added, about 2/3 of which don't exist.

I can test for the existence of the directory using [ ! -d $VARIABLE_TO_ADD_TO_PATH ], but if I find the directory doesn't exist, unsetting it seems to be harder.

I can write (for each of maybe 10 variables)

if [ ! -d $VAR ]
    unset VAR

but I'd rather have a function.

I tried:

   while [ $# -ge 1 ]
      if [ ! -d $dirToTest ]
         unset $1

passing in values in a form like _testPathAndUnset VAR1 VAR2 VAR3 (not $VAR1 $VAR2 $VAR3), but now I have strings which don't expand.

Using eval might solve this for me, but other questions, answers, websites etc etc suggest this is generally a bad idea.

How can I solve this problem in a better way than 30 lines of 10x3 ?

if [ ! -d $VAR ]
    unset VAR

Here is a function:

_testPathAndUnset() { for d in "$@"; do [ -d "${!d}" ] || unset "$d"; done; }

Here it is in use. To start with, we have two directories:

$ ls -d */
a1/  a2/

We define four shell variables which may or may not evaluate to directories:

$ one=a1; two=a2; three=a3; four=a4

Now, run our function against those four variables:

$ _testPathAndUnset one two three four

And, observe that only two variables remain set:

$ echo "one=$one two=$two three=$three four=$four"
one=a1 two=a2 three= four=


  • for d in "$@"

    This loops over every argument on the command line.

  • [ -d "${!d}" ] || unset "$d"

    Here d refers to the name of a variable. ${!d} refers to the value of the variable named d. This tests if the value of the variable named d is a directory. If it is not, the [ test evaluates to false and the unset "$d" clause is executed.

  • Perfect - thank you. The explanation is also very helpful. – chrisb2244 Oct 30 '14 at 3:04

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.