Jay Taylor's notes

back to listing index

bash - What does hash -r command do? - Ask Ubuntu

[web search]
Original source (askubuntu.com)
Tags: bash linux command-line shell-tricks $PATH hash askubuntu.com
Clipped on: 2020-03-02

This question already has answers here:
Closed 2 years ago.

I recently switched to linux full time from windows and while I was trying to update my npm package using n, I got the new binaries in /usr/local/bin and previous version was in /usr/bin. So, it was always picking the previous version.

As per recommendation by a fellow user, I used hash-r command and it worked. But, I don't know what it did.

It would be very helpful if someone could explain its internals to me.

Image (Asset 2/5) alt=

The shell tracks where executables such as npm reside to avoid having to search the PATH environment variable every time you want to run something.

  • The -r (reset) argument to hash clears the cache.

  • If you want to see what commands hash has remembered, simply type hash on its own without any arguments.

You can disable the cache altogether by typing set +h and re-renable it via set -h

answered Sep 2 '17 at 10:02
Image (Asset 3/5) alt=

hash is a built-in command of the bash shell. For a summary of what it does you can type help hash at the shell prompt:

$ help hash
hash: hash [-lr] [-p pathname] [-dt] [name ...]
    Remember or display program locations.

    Determine and remember the full pathname of each command NAME.  If
    no arguments are given, information about remembered commands is displayed.

    Options:
      -d    forget the remembered location of each NAME
      -l    display in a format that may be reused as input
      -p pathname   use PATHNAME as the full pathname of NAME
      -r    forget all remembered locations
      -t    print the remembered location of each NAME, preceding
            each location with the corresponding NAME if multiple
            NAMEs are given
    Arguments:
      NAME  Each NAME is searched for in $PATH and added to the list
            of remembered commands.

    Exit Status:
    Returns success unless NAME is not found or an invalid option is given.

So, hash remembers program locations, and hash -r forgets them.

answered Sep 2 '17 at 10:01
steeldriver
86.1k1212 gold badges146146 silver badges229229 bronze badges

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

Ubuntu and Canonical are registered trademarks of Canonical Ltd.