hash - Linux


Overview

The hash command in Linux is used primarily to manage the hash table of previously executed commands. It keeps track of the locations of commands, allowing for faster command execution by avoiding unnecessary path searches. This command is especially useful in scripts and session where commands in non-standard directories are executed frequently.

Syntax

hash [-lr] [-p filename] [-dt] [name ...]

Parameters

  • name: Specifies the command name(s) to work with the hash table.

Options/Flags

  • -l: List the current hash table’s contents in a reusable format.
  • -r: Reset the hash table, removing all entries.
  • -p filename [name]: Associate the name with the specified filename. This skips path search and uses the given filename as the path.
  • -d name: Remove specified entries from the hash table. You can list multiple names to delete multiple entries.
  • -t: Display the full pathname of each command name.

Examples

  1. List Hash Table:

    hash -l
    

    This command displays all entries currently in the hash table.

  2. Adding to the Hash Table:

    hash -p /usr/local/bin/script.sh script
    

    This associates the command name script with the path /usr/local/bin/script.sh.

  3. Resetting the Hash Table:

    hash -r
    

    Resets the hash table by removing all contents, useful when paths of executables change.

  4. Deleting from the Hash Table:

    hash -d script
    

    This command removes the entry for script from the hash table.

  5. Display Path:

    hash -t script
    

    Shows the full pathname linked to the command script.

Common Issues

  • Command not found: If you encounter this, it means the command’s path is either incorrect or not in the hash table.
  • Incorrect path after moving executables: After relocating executables, use hash -r to reset the hash table to avoid path errors.

Integration

Combine hash with scripting to speed up the execution of scripts that use commands from non-standard paths. For example:

#!/bin/bash
hash -p /opt/scripts/my_script.sh myscript
myscript arg1 arg2

In the script above, the use of hash avoids repeated path searches for myscript, speeding up the entire process.

  • type: Display information about command type.
  • which: Show the fully qualified path to a command.
  • alias: Allows creation of aliases for commands, not directly related but useful for customizing command names or defaults.

For further reading and advanced topics related to hash, you can check the official GNU Bash documentation online or consult the man pages by executing man bash in the terminal.