In this lesson, you will learn how your shell locates and runs programs when you type a command.
How the Shell Finds Your Programs
When you type a command into your terminal—like ls or cat—you are actually asking the shell to find a file on your hard drive, load it into memory, and execute it. But how does the shell know where these files live among the thousands of directories in your Linux system?
It uses a special environment variable called PATH. You can see your current search path by typing echo $PATH in your terminal. This variable contains a list of directories separated by colons, such as /usr/local/bin:/usr/bin:/bin.
The Resolution Process
When you type a command, the shell follows a strict order of operations:
- Check for Aliases/Functions: The shell first checks if you have defined a nickname or a function for that command.
- Consult the
PATH: If it isn't an alias, the shell scans the directories listed in your$PATHvariable, starting from the left and moving right. - Execution: As soon as the shell finds a file with that name that is marked as "executable" (a permission bit we will discuss later), it stops searching and runs that file.
Explicit Paths vs. Implicit Paths
If you want to bypass this search entirely, you can provide an absolute path or a relative path to the binary. For example:
/usr/bin/ls # Absolute path (starting from root)
./my_script.sh # Relative path (starting from current directory)
When you use a path that starts with / or ./, the shell doesn't bother checking the $PATH variable; it goes exactly where you tell it to go. If a file exists in the current directory but is not in your $PATH, you must use a prefix like ./ so the shell knows you are referencing a specific file rather than searching the system bins.
Key Takeaway: The shell searches the directories listed in your $PATH environment variable in order to locate binaries, unless you provide a specific file path to bypass the search.