How to add a directory to your PATH

How to add a directory to your PATH

Julia Evans
@b0rk one "fun" gotcha in bash is sometimes you have to run hash -r to clear a cache after updating PATH.
@nelson I really wanted to mention that but I tried to reproduce it and couldn't, do you know how to repro that issue?
@b0rk @nelson I have not had to rehash for a long time now. I assumed this was a legacy shell thing.

@lemay @b0rk @nelson The case where you used to need to do this is if you first run a command from the shell, then you change the PATH so that the same command is found in a different place, but it still exists in the original place. bash consults the hash table first. If it says that foo is found in /usr/bin/foo, then you change PATH to put /home/b0rk/bin first, and there's a foo in that directory, bash would still run /usr/bin/foo unless you reset the hash.

But I just tried this and it now appears that the hash table is cleared if PATH is changed. So I think hash -r is no longer needed.

@lemay @b0rk @nelson I take that back. There's a way to produce the issue, just confirmed.

If the PATH is not changed, you've run a command where bash found your program in, say, the 3rd directory, then you add a command of the same name in an earlier directory, bash will run the wrong command unless you do hash -r .

@lemay @b0rk @nelson Here's a reproducer, assuming ls originally finds /usr/bin/ls :

export PATH=/home/me/dummy:$PATH
ls /usr/bin/ls
touch /home/me/dummy/ls
chmod +x /home/me/dummy/ls
ls /usr/bin/ls

You need hash -r to get bash to run your new ls, because the first ls command put ls -> /usr/bin/ls in the hash table.