which Command Examples

If you are wondering where exactly is a certain program is located, simply use which on it. The which command locates an executable file in your shell’s search path.

This Linux command has a simple syntax:

which [-a] filename

Let’s see how to use this simple but useful command.

Linux which command examples

Let’s say you want to know where is the Java executable, use which command:

which java

The output could be like this:

abhishek@linuxhandbook:~$ which java
/usr/bin/java

Note that which only works on executable files. So you should use it only with the argument that you can run. For example, you install Java through the JDK package but you don’t run a command called ‘jdk’, you run ‘java’. So you use which command on java, not jdk.

If the which command doesn’t find the executable in the current path, it returns nothing.

Using which command with multiple executable files

You can provide more than one argument to which command:

which man java python nada

The output for me was:

abhishek@linuxhandbook:~$ which man java python nada
/usr/bin/man
/usr/bin/java
/usr/bin/python

Did you notice something here? I gave it four arguments but the result is displayed for three of them only. It’s because ‘nada’ is not an executable. There is no output for that.

Display all pathnames with which command

The which command in Linux has only one option, -a. By default, which command prints only one pathname for its arguments.

If a program has executable in two places, say in /usr/bin/program and in /usr/local/bin/program, you can display both pathnames using the -a option.

which -a <program_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.