LinuxCommandLibrary

hash

Remember and locate executable program locations

TLDR

View cached command locations for the current shell

$ hash
copy

Clear the hash table
$ hash -r
copy

Delete a specific command from the hash table
$ hash -d [command]
copy

Print the full path of command
$ hash -t [command]
copy

Display help
$ hash --help
copy

SYNOPSIS

hash [-lr] [-d name] [-p pathname name] [-t name] [name ...]

PARAMETERS

-d name, --delete name
    Delete the hashed entry for name from the table.

-l, --load
    List hashed commands in a format suitable for rehashing via shell eval.

-p pathname name
    Associate name with pathname directly, bypassing PATH search.

-r, --reset
    Reset (clear) the entire hash table.

-t name, --type name
    Print the type and/or path of name (file, alias, function, builtin).

DESCRIPTION

The hash command is a shell builtin in Bash and other POSIX-compliant shells like Dash and Zsh. It maintains an internal hash table that caches the full paths of executable commands found via the $PATH search.

When a command is executed without a leading slash (e.g., ls instead of /bin/ls), the shell probes directories in $PATH sequentially. Upon finding the executable, hash stores its full path to avoid repeated searches, improving performance in interactive sessions or scripts with frequent command calls.

Running hash alone lists all hashed commands in the format name => full/path. Specifying a command like hash ls forces a PATH lookup and caches it. The table persists for the shell session but is invalidated by PATH changes or new executables, often requiring hash -r to reset.

This optimization is crucial on systems with long PATHs or slow filesystems (e.g., NFS). However, it can lead to issues with moved binaries or symlinks, as stale entries are used until reset.

CAVEATS

Shell builtin only; use help hash in Bash or man bash. Table is session-specific and may cache stale paths after PATH changes or file moves—use hash -r to refresh. Not available in non-POSIX shells.

COMMON USAGE

hash
Lists all cached commands.
hash -r
Clears cache after PATH changes.
hash gcc
Caches path to gcc.

HASH CHECK

Use type -a command to see hashed path vs. current PATH resolution.

HISTORY

Introduced in the original Bourne shell (1977) for performance. Standardized in POSIX.1-2001 and later, with Bash enhancing options like -t for type info.

SEE ALSO

type(1), command(1), which(1), whereis(1)

Copied to clipboard