What is which?

which is a command-line utility available on Unix-like operating systems, including Linux and macOS. Its primary function is to locate the executable file associated with a given command. It searches the directories listed in the user's <a href="https://www.wikiwhat.page/kavramlar/PATH%20environment%20variable">PATH environment variable</a> to find the first occurrence of the command.

Key Features and Usage:

  • Finding Executables: The core function of which is to determine the full path to an executable file. For example, which ls would likely return /bin/ls.

  • Path Search: which uses the <a href="https://www.wikiwhat.page/kavramlar/PATH%20environment%20variable">PATH environment variable</a> to find executables. The PATH is an ordered list of directories where the shell searches for commands.

  • Multiple Matches: By default, which only returns the first matching executable. Some implementations, such as GNU which, offer options (like -a or --all) to display all matches found in the PATH.

  • Return Value: The exit status of which indicates success or failure. A return status of 0 typically means the command was found, while a non-zero status (often 1) indicates that the command was not found in the PATH.

  • Distinguishing from type: While type also provides information about commands, which is specifically focused on finding executable files in the PATH. type can also identify shell built-in commands, aliases, and functions.

  • Portability: which is widely available and generally conforms to the POSIX standard, making it a portable tool across different Unix-like systems.

Common Use Cases:

  • Verifying if a program is installed and accessible.
  • Identifying the location of a command to ensure you are using the intended version, particularly when multiple versions might be installed.
  • Troubleshooting path-related issues where commands cannot be found.