Skip to main content
Engineering LibreTexts

05-B.5.2: Searching for Files on Linux - which Command

  • Page ID
  • \( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)

    The which Command

    The which command returns the pathnames of the files (or links) which would be executed in the current environment, had its arguments been given as commands in a strictly POSIX-conformant shell. It does this by searching the PATH variable for executable files matching the names of the arguments.

    pbmac@ubuntu $ echo $PATH
    pbmac@ubuntu $ which ping
    pbmac@ubuntu $ which netcat uptime
    pbmac@ubuntu $ which -a touch
    pbmac@ubuntu $

     The PATH is the directories that Linux will look in to find an executable file when you attempt to issue a command, either from the command line, or selecting an icon on a GUI based system. in this example, Linux will sequentially search through each directory looking for the command, and will execute the first file that matches the user's input.

    which can accept a single argument, such as ping, or multiple arguments as shown with netcat and uptime; and if you use the -a option, it will show ALL of the files with the given name, not just the first one it finds. In the example it found two files named touch and lists the path to both files.

    The use of the -a option is a great tool to make sure you are executing the file you think you are executing. If there is another file named the same, and it is in your PATH before the file you want to execute, the first one gets executed. This can cause you to see output that is not what you expected, or different from what you expected.

    05-B.5.2: Searching for Files on Linux - which Command is shared under a CC BY-NC license and was authored, remixed, and/or curated by LibreTexts.

    • Was this article helpful?