Home > Articles

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

The Bash Hash Table

When a command is executed without naming a path, the shell searches for the command (in the directories listed in the PATH variable). When the Bash finds the command, it remembers where it is, storing the location in a hash table. Thereafter, Bash checks the table for the location of the command instead of searching for the command again, making commands run faster. However, if the command moves after Bash has recorded its location, the shell won't be able to find the command.

The built-in hash command maintains the hash table. Without any switches, hash lists the memorized commands, where they are, and the number of times the command has been executed during this session.

$ hash
hits  command
  1  /bin/ls
  1  /bin/uname
  1  /usr/bin/tput
  1  /bin/stty
  1  /usr/bin/uptime
  1  /usr/bin/man

When a command is specified, Bash searches for the new location of the command. For example, if you create your own ls command in your current directory, and the PATH variable gives precedence to files in your current directory, the hash ls command finds your ls command first, replacing /bin/ls with ./ls.

$ hash ls
$ hash
hits  command
  1  /bin/touch
  0  ./ls
  1  /bin/chmod

The -p (path) switch explicitly sets a path for a command. The -d (delete) switch deletes a specific entry, and -r (remove) clears the hash table, removing all commands. The –t (table) option lists the pathnames for specific commands, and -l (list) lists the commands in a format that allows them to be reused by the hash command.

$ hash -t ls less
ls   /bin/ls
less  /usr/bin/less
  • + Share This
  • 🔖 Save To Your Account