Skip to content
LumenaryAcademy
Foundations 45 min

The shell and the terminal

What a shell is, where Bash came from, how it reads and runs a command line, and your first script.

Code tested · 3AI-draftedAwaiting review by a computer scientist
MotivationH

Why the shell still matters

Open a terminal on almost any server in the world and you will be talking to a shell, very often Bash. The same is true of the scripts that build software, the run: steps in CI pipelines, the RUN lines in container files, the start-up scripts of virtual machines and the countless small automations that keep systems running. When something breaks at two in the morning, the person who can read and write shell is the one who can fix it.

The shell is also a remarkable glue language. A few words joined by | can search a gigabyte of logs, count the results and sort them, by connecting small programs that each do one thing well. That way of working, building big answers out of small tools, is one of the oldest and most durable ideas in computing.

But Bash is also full of traps. It was designed for typing commands interactively, its rules about spaces and quotes are unlike any other language you know, and a script that works on your test data can fail badly on a file name containing a space. This course teaches both halves: the power, and the discipline that makes shell scripts safe. We start with what a shell actually is.

DefinitionsH

Terminal, shell, command

Three things are easy to confuse, because they appear in the same window.

Definition— Terminal (terminal emulator)

The program that draws the window, shows text and sends your keystrokes on: GNOME Terminal, Konsole, Windows Terminal, the macOS Terminal, iTerm2, or the terminal panel in an editor. It knows nothing about commands. The name comes from the physical terminals (keyboard and screen, and before that a teletype) that people once used to talk to a shared computer.

Definition— Shell

The program that reads the commands you type (or a script contains), interprets them, starts other programs and reports their results. Bash, zsh, fish, dash and PowerShell are shells. The shell is just a program running inside the terminal: you can start another shell inside it by typing bash.

Definition— Command

What the shell runs. It may be a separate program on disk (like ls or grep), a builtin that is part of the shell itself (like cd or echo), a function you defined, an alias, or a keyword of the shell's own syntax (like if or for).

A shell runs in two modes. Interactively, it shows a prompt, reads one line at a time and runs it, and offers comforts such as history (press the up arrow, or Ctrl-R to search), tab completion and line editing. Non-interactively, it reads commands from a file: a script. The language is the same in both, which is why a sequence of commands you have tried by hand can become a script almost unchanged.

History & global context

From the Bourne shell to Bash 5.3

The first Unix shell was written by Ken Thompson in 1971. In 1979, Version 7 Unix shipped a new shell by Stephen Bourne of Bell Labs: sh, the Bourne shell, with variables, control flow and the syntax that every shell in this family still uses. Others followed, notably the C shell (1978) and the Korn shell (1983), which added interactive conveniences and better scripting features.

The Bourne shell was proprietary. The GNU Project, which was building a free Unix-like system, needed a free replacement, and Brian Fox wrote one: Bash, the "Bourne-Again SHell" (a pun on the name of the original author), first released in 1989. Chet Ramey of Case Western Reserve University has maintained it since the early 1990s. In 1992 the shell language itself was standardised as part of POSIX, so that scripts written for sh would work on any conforming system; Bash implements that standard and adds many extensions of its own.

Some milestones you will see referred to:

  • Bash 3.2 (2006) is still the version Apple ships with macOS, because later versions are licensed under GPLv3. Since 2019, macOS's default interactive shell has been zsh.
  • Bash 4.0 (2009) added associative arrays, mapfile, ** recursive globbing and ;& in case.
  • Bash 5.0 (2019), 5.1 (2020) and 5.2 (2022) added smaller conveniences such as EPOCHSECONDS, SRANDOM and new parameter transformations.
  • Bash 5.3 (2025) is the current version as of late 2026. It added, among other things, a form of command substitution that runs in the current shell without starting a new process, ${ command; }, and a GLOBSORT variable to control how file name matches are ordered.

Many Linux distributions (Debian and Ubuntu, for example) use the smaller, faster dash as /bin/sh, and keep Bash as the interactive shell. That is why a script that starts with #!/bin/sh must stick to POSIX features, while one that starts with a Bash shebang may use everything in this course. To see which Bash you are running, type bash --version or echo "$BASH_VERSION". The scripts in these lessons were run with Bash 5.1, and features from later versions are marked.

ComputationC

How Bash runs a command line

When you press Enter, Bash does not simply "run what you typed". It goes through a fixed sequence of steps, and almost every surprising thing Bash does is explained by one of them:

  1. Read the line (or several lines, if a quote or a block is still open).
  2. Split it into words and operators. Spaces and tabs separate words; characters such as |, ;, &, < and > are operators. Quotes stop splitting (next lesson).
  3. Expand the words: variables ($HOME), command substitutions ($(date)), arithmetic, ~, wildcards (*.txt) and more. This happens before any command runs.
  4. Set up redirections such as > out.txt (lesson 3).
  5. Find the command named by the first word: an alias, a keyword, a function, a builtin, or else a program found by searching the directories listed in the PATH variable, left to right.
  6. Run it with the remaining words as its arguments. For an external program, Bash creates a new process for it and waits for it to finish.
  7. Record its exit status in $?: 0 means success, anything from 1 to 255 means some kind of failure.

The builtin type tells you which kind of command a word is. In a script, type -t prints just the kind:

bash
#!/usr/bin/env bash
# What kind of command is each word? type -t answers: keyword, builtin, file, function or alias.
greet() { printf 'Hello, %s!\n' "$1"; }

for word in if cd echo printf greet ls grep; do
    printf '%-7s %s\n' "$word" "$(type -t "$word")"
done

greet "Wanjiru"
echo "Exit status of the last command: $?"
ls /no/such/place 2>/dev/null
echo "Exit status after a failed ls: $?"
text
if      keyword
cd      builtin
echo    builtin
printf  builtin
greet   function
ls      file
grep    file
Hello, Wanjiru!
Exit status of the last command: 0
Exit status after a failed ls: 2

cd must be a builtin: a separate program could change only its own current directory, not the shell's. echo and printf exist both as builtins and as programs (try type -a echo), and the builtin wins because builtins are found before PATH is searched. ls and grep are ordinary programs, typically in /usr/bin. The ls that failed returned status 2 (the GNU ls convention for "serious trouble"), and the 2>/dev/null threw away its error message; lesson 3 explains that piece of syntax.

Worked examplesH

Arguments, options and help

After expansion, the first word is the command and every other word is an argument. The program receives them as a list of strings; it never sees the spaces between them, the quotes around them or the wildcard that produced them. This little script makes the list visible. $# is the number of arguments a function (or script) received and "$@" is all of them:

bash
#!/usr/bin/env bash
# Every command line is split into words; the first word is the command, the rest are its arguments.
show_args() {
    printf '%d argument(s):\n' "$#"
    printf '  [%s]\n' "$@"
}

show_args one two three
show_args "one two" three
show_args 'single $quotes' "double: $((6 * 7))"
show_args          lots      of       spaces
text
3 argument(s):
  [one]
  [two]
  [three]
2 argument(s):
  [one two]
  [three]
2 argument(s):
  [single $quotes]
  [double: 42]
3 argument(s):
  [lots]
  [of]
  [spaces]

Notice how quotes kept one two as one argument, how the single quotes left $quotes untouched while double quotes allowed $((6 * 7)) to be calculated, and how extra spaces simply disappeared. The printf trick, a format reused for each remaining argument, is a handy debugging tool in its own right.

By convention, arguments that start with - are options. Short options are single letters and can usually be combined (ls -l -a is ls -la); GNU programs also accept long options (ls --all). An argument of exactly -- means "no more options follow", which is how you deal with a file whose name starts with a dash: rm -- -notes.txt. These are conventions, not rules enforced by the shell, so each program documents its own options. To find help:

You wantType
A program's manual pageman grep (press q to quit, / to search)
A quick summary from a GNU programgrep --help
Help for a Bash builtin or keywordhelp cd, help for
To know what a word istype -a echo
A program's locationcommand -v python3
Worked examplesH

Your first script

A script is a text file of commands. Here is a small one, laid out the way experienced people lay out even short scripts:

bash
#!/usr/bin/env bash
# greet.sh: greet each person named on the command line, or the world.
set -euo pipefail   # stop on errors and unset variables (lesson 7 explains this line)

main() {
    if (( $# == 0 )); then
        set -- "world"            # no arguments: pretend we were given one
    fi
    local name
    for name in "$@"; do
        printf 'Hello, %s!\n' "$name"
    done
    printf 'Greeted %d %s.\n' "$#" "$( (( $# == 1 )) && echo name || echo names)"
}

main "Amara" "Kenji" "Lucía"
main
text
Hello, Amara!
Hello, Kenji!
Hello, Lucía!
Greeted 3 names.
Hello, world!
Greeted 1 name.

A few things to notice, all explained properly in later lessons:

  • The first line is the shebang, #!/usr/bin/env bash. When you run a file as a program, the operating system reads this line to decide which interpreter to use. Using env finds bash wherever it is installed on PATH, which matters on systems (like macOS with a newer Bash installed) where /bin/bash is not the one you want.
  • Lines starting with # are comments.
  • set -euo pipefail makes the script stop at the first failing command instead of carrying on regardless. Lesson 7 explains each letter and its caveats.
  • The work is in a function called main. For the lesson the script calls main twice with fixed names; a real script would end with main "$@", passing on its own arguments.
  • printf rather than echo, because printf behaves the same everywhere, while echo's handling of options and backslashes differs between shells and systems.

To run a script, either pass it to Bash, or make it executable and run it by path:

text
bash greet.sh Ana Bo           # run it with bash explicitly
chmod +x greet.sh              # once: mark the file as executable
./greet.sh Ana Bo              # run it; the shebang chooses the interpreter

The ./ is needed because the current directory is (deliberately) not on PATH: otherwise a malicious file named ls in some directory could run when you typed ls there.

ExplanationH

Living at the prompt

Most of your time with Bash will be interactive, and a few habits make it far more pleasant. Everyday navigation uses a handful of commands: pwd (where am I?), cd dir (go there; cd alone goes home, cd - goes back to the previous directory), ls -l (what is here, in detail), mkdir -p a/b/c, cp, mv, and rm, which deletes immediately and has no undo, so read an rm command twice before pressing Enter. ~ means your home directory.

The keys that experienced users press without thinking:

KeyEffect
Tabcomplete a command, file name or option; press twice to list the choices
Up and down arrowsstep through previous commands
Ctrl-Rsearch your history as you type; Enter runs the match
Ctrl-A, Ctrl-Ejump to the start or end of the line
Ctrl-W, Ctrl-Udelete the previous word, or everything before the cursor
Ctrl-Cinterrupt the running command (or abandon the line you are typing)
Ctrl-Dend of input: exits the shell at an empty prompt
Ctrl-Lclear the screen
Ctrl-Zsuspend the running command (lesson 8 shows how to resume it)

These line-editing keys come from the Readline library, which Chet Ramey also maintains and which many other programs use, so they work in the Python REPL, database shells and more. Your settings live in ~/.bashrc, a script that interactive Bash shells run at start-up (a login shell reads ~/.bash_profile instead, which on most systems loads ~/.bashrc too): that is where people put aliases (alias ll='ls -l'), their preferred prompt and additions to PATH.

Common misconceptionsH

Common misconceptions

Misconception

"The terminal is the shell." The terminal draws text; the shell interprets commands. You can run zsh, fish or Python's REPL in the same terminal, and you can run Bash with no terminal at all, as a script.

Misconception

"sh is just another name for Bash." On many systems /bin/sh is dash, a smaller POSIX shell, and Bash features such as [[ ]], arrays and {1..5} do not work there. A script that uses Bash features must say so in its shebang and be run with bash.

Misconception

"Spaces don't matter much." In Bash they are syntax. name=Ana assigns a variable; name = Ana runs a command called name with two arguments, = and Ana, and fails with "command not found".

Misconception

"A command that printed an error must have stopped the script." By default Bash carries on to the next line whatever happened. Success and failure are reported only through the exit status, and it is up to the script to check it (lesson 4) or to ask Bash to stop on failure (lesson 7).

Exercises

Exercises

Try the commands in a terminal as you go. For the "what does it print" questions, predict first, then check with bash.

1. The shell and the terminal

Warm-upHuman

You open Windows Terminal, start a WSL session, and type ls. Which program reads and interprets the line ls?

Choose one

2. The shell and the terminal

Warm-upComputational

Someone types name = Ana meaning to set a variable. Bash prints name: command not found. What is the exit status in $? afterwards?

3. The shell and the terminal

CoreComputational

With the lesson's show_args function, how many arguments does this call receive?

show_args "a b" c 'd e f'

4. The shell and the terminal

StretchComputational

How many arguments does this call receive?

show_args   x"y z"   w

5. The shell and the terminal

Warm-upComputational

What does type -t cd print in Bash?

6. The shell and the terminal

CoreHuman

Why is cd built into the shell rather than being a program in /usr/bin like ls?

Choose one

7. The shell and the terminal

CoreComputational

A script uses Bash arrays and [[ ... ]]. It works when run as bash deploy.sh, but fails with syntax errors on an Ubuntu server when run as ./deploy.sh. Its first line is #!/bin/sh. What is the most likely cause?

Choose one

Further reading and resources