Skip to the workspace
Pebellslearn by building
Shell and Other Basics  ›  Lesson

The Command Path — How the Shell Finds Programs

Command Path 12 minWhen a command name has no slash, the shell searches the directories in PATH from left to right and runs the first match.

linux / The Command Path — How the Shell Finds Programs

Explore each scene at your own pace.

01 · The rule

The rule

The Command Path — How the Shell Finds Programs

When Asha types ls, she never says where the ls program is. The shell finds it anyway. Later she writes her own script, harvest-report, types its name, and gets command not found even though the file is right there in front of her. Both of these come down to one variable.

The rule

The shell searches PATH left to right; the first match wins.

PATH is a list of directories separated by colons:

$ echo $PATH
/home/asha/bin:/usr/local/bin:/usr/bin:/bin

When you type a command name without a slash, the shell checks each directory in that list in order, and runs the first file with that name that it's allowed to execute. If no directory has one, you see command not found.

The shell does not look in the current directory unless it's on the list, and for safety it normally isn't. That's why a script sitting right next to you has to be run with a path:

$ ./harvest-report          # a path with a slash: skip the search
$ ~/garden/harvest-report   # also a path

To ask the shell what a name will run:

$ type ls
ls is aliased to `ls --color=auto'
$ command -v python3
/usr/bin/python3
$ which python3
/usr/bin/python3

type is the most honest of the three because it also knows about aliases, functions and builtins (commands such as cd that live inside the shell itself). The shell checks those before it searches PATH at all.

To make her own scripts runnable from anywhere, Asha puts them in ~/bin and adds that folder to the front of her PATH:

export PATH="$HOME/bin:$PATH"
Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.