The which command locates the executable command or file location in the user’s environmental path. It will give you the complete path of executable command or file pointing towards in your file system.
|Root or Sudo Privileges||No|
|OS Compatibility||Ubuntu, Manjaro, Fedora, etc.|
Syntax of the Which Command
The command takes two arguments: one is the option, and the other is the executable command or file name.
$ which [OPTION] [FILENAME]
You can specify multiple executable commands or file names by using the space as a separator.
Using the Which Command
Let’s say you want to find the full path of the ls command; for that, use the which command and specify “
ls” as an argument.
$ which ls
As you can see above, the full path of the ls command is “
/usr/bin/ls” in your system.
If you want to find out the complete path of the echo command, then specify “
echo” as an argument to which command.
$ which echo
The complete path of the echo command is “
/usr/bin/echo” in your system.
Note that the which command only takes the command or file name that is executable from your terminal.
If you specify a command that is not executable, it will not print its location as shown.
$ which wrongcommand
Because the path used to search for files is located in the environmental files, if you search for files or a command that is not executable from your terminal, it will throw you an exit status code.
Using the Which Command with Multiple Arguments
You can provide multiple executable commands or files as an argument to locate their paths.
$ which ls echo
As you can see above, you can use space as a separator to get the paths of multiple commands at the same time.
Display All Pathnames with Which Command
By default, the which command will only print the active executable command or file you use to execute from your terminal.
However, if the same executable command or file exists in multiple locations, like “
/bin/” or “
/usr/bin/program” or “
/usr/local/bin/program“, you can use the “
-a” flag with an argument to display both pathnames.
Finding all paths for a single executable command or file:
$ which -a ls
Finding all paths for multiple executable commands or files:
$ which -a ls echo
Exit Status of Which Command?
The exit status of which command might come into use when you write a shell script to control the follow of your script by the exit status.
The which command has three exit statuses, followed by:
0– All specified commands and files are found.
1– If one or more specified commands or files are nonexistent or not executable.
2– If an invalid option is specified.
That’s all you need to know about this command.