which command in Linux

Do not miss this exclusive book on Binary Tree Problems. Get it now for free.

The which command locates executable files associated with a given command. In this article we discuss it and cover commonly used which commands.

Table of contents.

  1. Introduction.
  2. Syntax.
  3. Commands.
  4. Summary.
  5. References.

Introduction.

The which command is used for locating executable files which are associated with a given command.
Its returns 0 if the specified command's file is found and it is an executable.
1 is if the command(s) does not exist or it cannot be executed.
2 if an invalid option is specified.

Syntax.

The syntax is as follows,

which [-a] filename ...

In this case -a option is used to print all matching pathnames for every matching file.

Commands.

To display the paths for the ping command we write,

which ping

To display all matching paths, we use the -a option,

which -a ls

To find the path of sudo we write,

which sudo

We can also pass multiple arguments as follows,

which ls ping mkdir

The above command returns the path for ls, ping and mkdir commands.

To view the exit status after a command has executed, write,

echo $?

Summary.

The which command locates a command by searching its executable in the specified directories by PATH environment variable.
PATH tells the shell and other programs which directories to search for executable files.

To view its contents write,

echo $PATH

Having located the executables, we might be curious to reads their contents however concatenating for example cat /usr/bin/ping won't produce human readable output. To obtain human readable strings, we use the strings command which we have covered in another article. The link is provided below.

References.

  1. Execute the command man which for its manual pages.
  2. strings command in Linux
  3. whereis

Sign up for FREE 3 months of Amazon Music. YOU MUST NOT MISS.