Use “which” in Linux to find the Location of an Exetable

Linux comes with the which command to locate a given executable. Executables are commands you type into your terminal, like git, node, touch, or vim.

Sometimes, you want to find the location of an executable on your filesystem. That’s where the which command comes handy. Read on to find out how to use which!

Ubuntu/Debian Series Overview

Locate an Executable in Linux With which

Using which parses the PATH environment variable to find all locations to search for a program.

How to use the which command

The which command has the following syntax:

 which [OPTIONS] COMMAND

For example, you may locate the git program like this:

$ which git
/usr/bin/git

You can also locate more than one program in a single call by adding all programs separated by a space:

$ which git node vim
/usr/bin/git
/usr/local/bin/node
/usr/bin/vim

Using Options

The which command supports two options:

-a      List all instances of executables found (instead of just the first one of each).

-s      No output, just return 0 if all of the executables are found, or 1 if some were not found.

If a command is present in multiple locations, you can find all occurrences using the -a option.

Using -s changes the output of which when programs are not found. Let’s say you don’t have MongoDB installed. Trying to locate the mongod executable results in different outputs depending on whether you append the -s option:

$ which mongod
# no output at all

# and with the “-s” option
$ which mongod
mongod not found  

The -s option allows you to retrieve expressive results. This is helpful when you as a human runs the command. In shell scripts, you may want to check for empty outputs to determine whether an executable is missing.

Enjoy!

Explore the Library

Find interesting tutorials and solutions for your problems.