When you install multiple versions of the same software on a Linux machine (such as having Python 2.7 and Python 3.10 installed simultaneously), typing a simple command like python into the terminal can lead to unexpected results. If a script fails because it executed the wrong version of a binary, you need to know exactly which executable file the system is prioritizing. To quickly locate the exact path of the binary file that your shell will run, you should use the which command.
How the which Command Works
In Linux, when you type a command (like ls or nano) without providing a full path, the shell searches through a specific list of directories to find the executable file. This list of directories is stored in an environmental variable called the $PATH.
The which command simply searches the directories listed in your $PATH from left to right. When it finds an executable file matching the name you provided, it instantly prints the absolute path to the terminal and stops searching. This tells you exactly what binary will execute when you run the command.
Basic Usage
Using the command is incredibly straightforward. Simply type which followed by the name of the program you want to locate.
which python3
If the executable exists in your $PATH, the output will look something like this:
/usr/bin/python3
If the command does not output anything at all, it means the executable file was not found in any of the directories listed in your $PATH variable. You either mistyped the command name, the software is not installed, or the software is installed in a custom directory (like /opt/) that hasn’t been added to your $PATH.
Locating All Instances (The -a Flag)
By default, which stops searching the moment it finds the first match. However, if you are debugging a complex environment and suspect there might be competing binaries, you can force the command to search the entire $PATH and print every single match it finds. To do this, use the -a (all) flag.
which -a node
The output might reveal multiple installations, confirming an environment conflict:
/home/user/.nvm/versions/node/v18.0.0/bin/node
/usr/local/bin/node
/usr/bin/node
In this scenario, because the NVM (Node Version Manager) path is listed first, that is the binary the system will execute, effectively overriding the system-wide installations located lower down in the $PATH hierarchy.