Linux which Command

Locate Executables in PATH

Command Overview

which locates the executable file associated with a given command by searching through the directories listed in the PATH environment variable. It shows which version of a command will be executed when you type it in the shell. This is particularly useful when multiple versions of a command exist on the system.

Example 1: Find Single Command

which python3
/usr/bin/python3

Shows the full path to the python3 executable that would be executed.

Example 2: Find Multiple Commands

which python python3 pip
/usr/bin/python /usr/bin/python3 /usr/bin/pip

Searches for multiple commands at once, displaying the path for each.

Example 3: Show All Matches in PATH

which -a python3
/usr/bin/python3 /usr/local/bin/python3

The -a option displays all matching executables in PATH, not just the first one found.

Example 4: Check Non-Existent Command

which nonexistentcommand

Returns no output when command is not found in PATH. Exit status is non-zero (failure).

Example 5: Use in Scripts for Validation

if which docker &>/dev/null; then echo "Docker is installed" else echo "Docker not found" fi
Docker is installed

Common pattern in scripts to verify a command exists before attempting to use it.

Example 6: Check Shell Built-ins vs External Commands

which cd which ls
/usr/bin/ls

The cd command returns nothing because it's a shell built-in, not an external executable. ls is an external command and shows its path.

Example 7: Find Commands and Follow Symlinks

which python ls -l $(which python)
/usr/bin/python lrwxrwxrwx 1 root root 7 Mar 15 2024 /usr/bin/python -> python3

Combines which with ls to show if the command is a symbolic link and where it points.

Example 8: Compare with Command Location

which gcc whereis gcc
/usr/bin/gcc gcc: /usr/bin/gcc /usr/lib/gcc /usr/share/man/man1/gcc.1.gz

Shows difference between which (PATH only) and whereis (multiple file types).

Example 9: Check PATH Order Priority

echo $PATH which -a python3
/usr/local/bin:/usr/bin:/bin /usr/local/bin/python3 /usr/bin/python3

Shows which version takes priority based on PATH order. First match is executed.

Example 10: Alternative - Use type Command

type python3 type -a python3 type cd
python3 is /usr/bin/python3 python3 is /usr/bin/python3 python3 is /usr/local/bin/python3 cd is a shell builtin

The type command is more comprehensive than which as it shows builtins, aliases, functions, and executables.

Additional Information

Common Options

Alternatives

Pro Tip: Use type instead of which in scripts for better portability and to detect shell builtins, aliases, and functions.