Which command in Linux|Unix with examples

Which command is a frequently used command to find the location of executable files in Linux/Unix

During application development, I can use this command to locate the tomcat location for log finding.

In this tutorial, We are going to learn about which command and syntax and usage examples.

Syntax:

which options [string array]

This command accepts,

  • options
  • -a displays all pathnames of the given input string
  • string is an input filename which compared and checked against PATH folder paths

Returns the list of the path of filenames

Before returning this command, It returns the following exit codes 0 - given filename matched with executable paths 1 - filename(s) are not executable found 2 - It returns if an option is an invalid argument,

print all matching pathnames of each argument which command search for the executable files configured to the environment variable PATH

PATH is an environment variable that contains all the directories pointed to executable files

First, print the PATH environment values using the echo command

$:~$ echo $PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin

For example, to check where is git command is installed on a Linux machine.

$:~$ which git
/usr/bin/git

git command executable found in the /usr/bin folder

which command options

Please see the below example with and without options.

-a option prints all matched pathnames for a given input string

$:~$ which git
/usr/bin/git

$:~$ which -a git
/usr/bin/git
/bin/git

$:~$

print the which command documentation using info which command

WHICH(1) General Commands Manual WHICH(1)
NAME
which - locate a command
SYNOPSIS
which [-a] filename ...
DESCRIPTION
which returns the pathnames of the files (or links) which would be executed in the current environment, had its
arguments have been given as commands in a strictly POSIX-conformant shell. It does this by searching the PATH for
executable files matching the names of the arguments. It does not canonicalize path names.
OPTIONS
-a print all matching pathnames of each argument
EXIT STATUS
0 if all specified commands are found and executable
1 if one or more specified commands are nonexistent or not executable
2 if an invalid option is specified

Sometimes which command does not work or does not return anything on console

Then you can use whereas command same as which syntax.

Which command is used to which command?

which command is used to search the given string against a list of path values and print the complete path of an executable file.

For example,

which java

output:

/opt/lib/java

What is which command in Ubuntu?

Which is a command used to print the executable complete string of a string. It searches for all values path environment variables and prints output.

Conclusion

This article shows how to clear the terminal commands from different Operating Systems.