How the Shell Runs Commands
Prerequisites: Your first commands
When you press Enter, Bash does roughly this:
- Splits the line into words (the command and its arguments).
- Expands special characters — variables, wildcards,
~— into their values. - Finds the command.
- Runs it and waits for it to finish.
Where commands come from
A command can be:
- a builtin — part of Bash itself, like
cd,echo, andread; - an external program — a file somewhere on disk, like
ls,grep, orgit; - a function or alias you (or your configuration) defined.
Bash finds external programs by searching the folders listed in the
PATH variable, in order. type tells you what a command is:
type cd
type echo
type if
cd is a shell builtin
echo is a shell builtin
if is a shell keyword
# illustrative
type ls
echo "$PATH"
ls is /usr/bin/ls
/usr/local/bin:/usr/bin:/bin
Getting help
man ls— the full manual page for a program (pressqto quit,/wordto search).ls --help— a quick summary for most GNU programs.help cd— help for Bash builtins.- tldr pages (
tldr tar) — short, practical examples, if installed.
Exit status
Every command finishes with an exit status: 0 means success, and
anything else means failure. $? holds the status of the last command:
ls /this/does/not/exist
echo "exit status: $?"
echo "hello" > /dev/null
echo "exit status: $?"
ls: cannot access '/this/does/not/exist': No such file or directory
exit status: 2
exit status: 0
Exit statuses are how scripts decide what to do next — a whole later lesson covers them.