When you type a command like python or nano into the Linux terminal, the operating system instantly knows which program to launch. It achieves this by searching through a predefined list of system directories (known as your PATH) to find the executable binary file associated with that name. However, if you have multiple versions of a program installed (such as Python 2 and Python 3), you might not know exactly which version is executing when you type the generic command. To find out exactly where an executable binary is located on your hard drive, you must use the which command.
How to Use the which Command
The which command is incredibly simple to use. You simply pass it the name of the command you are trying to investigate.
which python
The output will be a single line displaying the absolute file path to the executable binary that the terminal will run if you type “python”. For example, it might output:
/usr/bin/python
If you type a command that does not exist, or an executable that is not currently located inside your system’s PATH directories, the which command will simply return nothing and drop you back to the prompt.
Finding All Matching Executables
By default, the which command stops searching as soon as it finds the very first matching executable in your PATH. This makes sense because the terminal also stops searching and executes the first match it finds. However, if you are debugging a complex environment and want to see if there are other versions of the program hiding in other directories, you can use the -a (all) flag.
which -a python
This forces the tool to search every single directory listed in your PATH variable and print all matches. Your output might look like this:
/usr/local/bin/python
/usr/bin/python
This output tells you that there are two separate Python installations on the system, but because /usr/local/bin appears first in your PATH, that is the version the terminal will prioritize.
Limitations of the which Command
It is important to remember that the which command only searches for executable binaries located within your PATH variable. It does not search your entire hard drive like the find command does. Additionally, it cannot identify shell aliases or built-in shell functions (like cd or echo). If you run which cd, it will likely return nothing, because cd is an internal feature of Bash, not an independent binary file sitting in a system folder. For identifying aliases, you must use the type command instead.