In this lesson, you will learn how your shell identifies the exact location of a program when you type a command.
The Problem of Binary Discovery
When you type a command like ls into your terminal, the shell does not inherently know where the ls binary lives on your disk. Searching the entire hard drive every time you hit "Enter" would be incredibly slow and inefficient. Instead, the shell relies on a specific environment variable called PATH.
The PATH Variable
The PATH variable is a colon-separated list of directories where the shell should look for executable files. You can see your current search path by running:
echo $PATH
When you type ls, the shell splits the value of PATH into individual folders. It then checks each folder in order, from left to right. It looks for a file named ls that has "execute" permissions. The moment it finds a match, it stops searching and runs that specific file. If it checks every directory in the list and finds nothing, it gives you the classic command not found error.
Verification with which
Because the shell follows this strict order, it is possible to have multiple programs with the same name in different folders. To see which version of a command the shell is actually resolving, you can use the which command:
which ls
# Output: /usr/bin/ls
If you have your own scripts in a custom folder, you could add that folder to your PATH so the shell can find them just as easily as it finds system tools. This mechanism is the reason why "installing" a program often involves placing a binary into a directory already listed in your PATH (like /usr/local/bin), ensuring that your shell can "resolve" the command immediately upon request.
Key Takeaway: The shell resolves commands by iterating through the directories listed in the PATH variable and executing the first match it finds.