which Command in Linux

Learn via video courses
Topics Covered

Overview

The 'which' command in Linux is a small but incredibly useful utility that helps users locate executable files within the system's PATH. It's an essential tool for system administrators, developers, and Linux enthusiasts who want to quickly identify the location of a binary file, script, or other executable they wish to use or debug.

Syntax of which Command in Linux

The basic syntax of the which command in Linux is as follows:

Where:

  • [options]: The options, also known as flags, modify the behavior of the 'which' command. For example, '-a' will print all matching pathnames of each argument.
  • [command_name]: This is the name of the executable file you want to locate. It is the main argument to the 'which' command.

Options in which Command in Linux

  1. -a: Prints all matching pathnames of each argument.

    For example -

    Output:

    This command displays all the paths where 'python' executable is located.

  2. -i: Ignores case distinctions while matching.

    For example -

    Output:

    This command will find 'python' even though the case doesn't match exactly.

Example Usages

  • Finding the path of an executable.:

    Output:

    Explanation: This command prints the path of the 'ls' command.

  • Finding the path of multiple executables at once.:

    Output:

    Explanation: This command prints the paths of both 'ls' and 'python' commands.

Tips

  • If the 'which' command does not find the executable, it could be that the PATH environment variable is not set correctly, or the executable is not in any directory listed in PATH.

  • The 'which' command only works for executables, not for shell built-in commands.

Advanced Use Cases of which Command in Linux

  • Using 'which' command with command substitution to check if a program is installed.:

    Output:

    Explanation: This command checks if 'python' is installed and prints a message with its path.

  • Finding the path of a command and navigating to its directory.:

    Explanation: This command changes the current directory to the one containing the 'python' executable.

Conclusion

  • The 'which' command in Linux is a simple and effective tool for locating the paths ofexecutable files.

  • 'which' operates by searching through the directories listed in the PATH environment variable.

  • It is important to remember that 'which' can only locate executables, not shell built-in commands.

  • The '-a' and '-i' options can be particularly useful for displaying all matching pathnames and ignoring case distinctions, respectively.