How to use which command.

How to use which command.

In this tutorial, we will cover the Linux which command.

Linux which command is used to identify the location of a given executable that is executed when you type the executable name (command) in the terminal prompt. The command searches for the executable specified as an argument in the directories listed in the PATH environment variable.

 

What is PATH

In Linux, PATH is an environmental variable that tells the shell and other programs which directories to search for executable files. It consists of a list of colon-separated absolute paths to directories containing the executables.

To view the contents of your PATH variable, use the echo command with $PATH as an argument:

echo $PATH

The output will look something like below:

/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

 

How to Use the which Command

The syntax for the which command is as follows:

which [OPTIONS] FILE_NAME...

For example, to find the full path of the ping command , you would type the following:

which ping

The output will be something like this:

/usr/bin/ping

You can also provide more than one arguments to the which command:

which netcat uptime

The output will include full paths to both netcat and uptime executables:

/bin/netcat
/usr/bin/uptime

The search is done from left to right, and if more than one matches are found in the directories listed in the PATH path variable, which will print only the first one. To print all matches, use the -a option:

which -a touch

The output will show two full paths to the touch command :

/usr/bin/touch
/bin/touch

Usually one of the executables is only a symlink to the other one, but in some cases, you may have two versions of the same command installed in different locations or totally different commands using the same name.

 

Conclusion

The which command is used to locate a command by searching the command executable in the directories specified by the environmental variable PATH.