which - Linux


Overview

The which command in Linux is used to locate the executable file associated with a given command by searching through the directories listed in the PATH environment variable. This command is primarily useful for determining which version of a program will be executed when called from the command line, especially when multiple versions are installed on the system. It is often used in scripting and debugging to verify path configurations.

Syntax

The basic syntax of the which command is:

which [options] [--] program_name [...]

Where program_name is the name of the command you want to locate. Multiple program names can be specified to locate their executables in succession.

Options/Flags

  • -a, --all: Print all matching executables in PATH, not just the first.
  • -i, --read-alias: Read alias from standard input, showing the aliases for each program_name.
  • --skip-alias: Do not print aliases (default behavior).
  • --show-dot: If the path is in the current directory, show it with a leading ‘./’.
  • --skip-dot: Do not check the current directory.
  • --skip-tilde: Skip directories that start with a tilde (which are typically user home directories).
  • --version: Display version information for which.
  • --help: Display usable help for the command.

Examples

  1. Find the executable for a single program:

    which python
    

    This will show the path to the Python interpreter executable that will be used when python is called.

  2. Find all occurrences of an executable in PATH:

    which -a python
    

    Lists all executables named python found in the directories listed in your PATH.

  3. Exclude current directory from search:

    which --skip-dot script.sh
    

    This will find script.sh but skip checking the current directory even if it’s in the PATH.

Common Issues

  • Command not found: If which does not return a path for a given command, ensure that the command is correctly installed and that your PATH environment variable is properly configured to include the directory where the command resides.
  • Multiple versions causing confusion: Running which -a <command> can help identify all installed versions of a command to avoid confusion over which is being executed.

Integration

which can be integrated with shell scripts to dynamically determine the path of executables:

editor=$(which vim || which nano)
$editor filename

This script will edit filename with vim if it’s installed, otherwise, it will fall back to nano.

  • whereis: Locates the binary, source, and manual page files for a command.
  • type: Indicates how a command name is interpreted in the shell.
  • find: Searches for files in a directory hierarchy.

For further reading or more in-depth details regarding the which command, the GNU Core Utilities documentation can be a valuable resource.