Linux Labs

First steps / Stage 14 of 15

Help and the shell

Not running Starting usually ~20 s
Leave the lesson

Step 2 of 8 · on a machine · 5 min

Where Bash looks for a command

When you type cp, you do not say where the program lives: the shell finds it on its own. echo $PATH and type show where it looks.

If a command name has no /, Bash first checks its own builtins, such as cd and pwd. Then it looks for a file with that name in the directories of PATH. PATH is an environment variable: a named value the shell passes to the programs it starts. Its value is a list of directories separated by colons.

bash
echo $PATH
type cp
type cd
type lab-status

echo $PATH prints that list: on the training machine it starts with /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin. The directories are checked left to right, and the first file found is the one that runs.

type shows what Bash found for a name: cp is /usr/bin/cp is a file from PATH, cd is a shell builtin is a builtin, and not found means nothing. If cp has already run in this shell, type prints cp is hashed (/usr/bin/cp): Bash remembered the path it found.

If the name contains /, there is no lookup: ~/tools/lab-status and ./lab-status point straight at the file. The dot in ./lab-status is the current directory, as in the lesson on paths.

Check yourself 1 question

You change to ~/tools and type lab-status. What does the shell print?

  • The current directory is not in PATH, and Bash does not check it. From that directory ./lab-status works.

  • Things never get as far as running: the name is neither a builtin nor in a PATH directory. type lab-status prints not found.

  • type only shows what the lookup finds and changes nothing. Run type lab-status twice — the output stays the same.

For a name without /, Bash goes through the PATH directories, and the current directory is not among them. A file right here is run by its path: ./lab-status.

Key points

  • Bash looks a name without / up among the builtins, then in the PATH directories from left to right.
  • A name with / is a path to a file: ./lab-status runs the file in the current directory without a lookup.
  • type name shows what will run: a builtin, a file from PATH, or nothing.
Ubuntu 24.04
Loading…