This tutorial will teach you how to use the which command in Linux with some simple examples.
The which command will tell you the path to the executable used by a command on the system if it exists.
Why is this useful? Say you’ve got two copies of the MySQL executable installed on your system (installed via different means), and you want to know which one is actually in use so that the other can be removed – the which command can tell you which of the two is called when you execute MySQL on the command line.
Linux which Command Syntax
The command for the which command is as follows:
which OPTIONS COMMAND
- OPTIONS is an optional list of options from the below table which can be used to change the default behavior of the which command
- COMMAND is the name of the command you wish to know the path to the executable for
- The COMMAND must be supplied, or which will have nothing to look for!
Here are the most commonly used options which can be passed to the which command:
|Print all matching executables in PATH, not just the first.
|Read aliases from stdin, reporting matching ones on stdout. This is useful in combination with using an alias for which itself.
|Ignore option –read-alias’, if any. This is useful to explicitly search for normal binaries, while using the –read-alias’ option in an alias or function for which.
|Read shell function definitions from stdin, reporting matching ones on stdout. This is useful in combination with using a shell function for which itself.
|Ignore option –read-functions’, if any. This is useful to explicitly search for normal binaries, while using the –read-functions’ option in an alias or function for which.
As always, you can view the full user manual for the which command by running:
which Command Examples
Below, we look for the path for the executable, which is called when nano is run from the terminal:
This will return something like the following if the nano text editor is installed on your system:
If nano is not installed, you’ll see:
nano not found
This makes the which command useful for both checking where an executable is located and whether a package is installed/available or not.
Multiple executable names can be supplied if you wish to look up multiple commands at once:
which cat less
Which will return:
If you are using which in a Shell Script, you can use the status code returned by the command to determine whether an executable path was found or not:
|All specified commands were found and are executable.
|One or more of the specified commands was not found or is not executable.
|Invalid options or syntax were used.
This can be super useful if you want to make your shell scripts more portable – you can use the which command to check that a command is available before executing it in your script, to make sure the end-user doesn’t receive any errors if they do not have the required software installed.