How To Use Linux Which Command

Photo of author

By rasho

The which command in Linux is used to locate any command in Linux. A command is essentially an executable that you can run. The command searches for the executable specified as an argument in the directories listed in the PATH environment variable.
In other words, if you are wondering where exactly is a certain program is located, simply use which on it.

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

Linux which command examples

The Linux command has a simple syntax:

which [-a] filename

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

which ifconfig

The output could be like this:

rasho@Gandalf:~$ which ifconfig
/sbin/ifconfig

Using which command with multiple executable files

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:

rasho@Gandalf:~$ which netcat uptime
/bin/netcat
/usr/bin/uptime

[ads]

Display all pathnames with which command

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:

rasho@Gandalf:~$ which -a touch
/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.

Exit status of which command

If you use which command in a bash script, you may need to know its exit status.
Which command has the following exit status:

  • 0 – all arguments are found and executable
  • 1 – one or more arguments is nonexistent or non-executable
  • 2 – if an invalid option is specified

That’s all you need to know about which command in Linux. If you have questions or suggestions, do let me know in the comments below.

Conclusion

The which command is used to locate a command by searching the command executable in the directories specified by the environmental variable PATH. If you have any questions please don’t forget to comment out.

Leave a Comment