Introduction to Bash
What a shell actually is, why Bash still runs servers, containers and CI pipelines, how a command line is put together, and how to get help without leaving the terminal.
By The Dark DebuggerUpdated 25 min read
This is the first article in the Bash track. It explains what the terminal and the shell are,
how Bash relates to sh and zsh, how to read any command line you come across, and how to
look things up when you're stuck. You don't need any prior command-line experience. If you
don't have a terminal with Bash yet, read Setting Up Bash and Your Terminal
first and come back. Every command here is meant to be typed, so keep a terminal open next to
this page.
Why the shell is still worth learning
Picture the situation: customers report that checkout on your web shop fails "sometimes". The web server is a Linux machine in a data centre. It has no desktop, no file manager and no mouse, only an SSH connection and a shell. The access log has a couple of thousand lines in it.
With one line typed at the prompt, you can ask the log which pages returned server errors (HTTP status 500 and above) and how often:
awk '$9 >= 500 {print $7}' access.log | sort | uniq -c | sort -rn | head -5 12 /checkout
5 /
4 /static/style.css
4 /products/1042
4 /api/ordersTwelve failures on /checkout, more than on any other page. That took a few seconds, and the
same line works on a log with ten million entries. You don't need to understand it yet. It is
four small programs (awk, sort, uniq, head) connected with pipes (|), and by the time
you reach Redirection and Pipes and
awk: Processing Columns and Records you'll be able to
write it yourself.
This is what the shell is for. It isn't nostalgia, and it isn't a place to show off. It lets you talk directly to machines that have no graphical interface, and that describes most of the computers that run the internet:
- Servers. Almost every Linux server you log into over SSH puts you in Bash.
- Containers.
RUNlines in a Dockerfile are shell commands, and debugging a running container usually means getting a shell inside it. - CI/CD pipelines. Jenkins
shsteps, GitHub Actionsrun:blocks and GitLab CIscript:lines are all shell scripts on Linux runners. - Scheduled jobs. cron runs its jobs with a shell, so backups, log rotation and report generation are usually shell scripts.
Learning Bash means you can read and fix all of those.
Terminal, shell and console are three different things
People use these words interchangeably, and that causes confusion as soon as something breaks. They are separate layers:
| Term | What it is | Examples |
|---|---|---|
| Terminal (terminal emulator) | The window. It draws characters, handles fonts, colours and copy/paste, and sends your keystrokes to the program inside it. | Windows Terminal, GNOME Terminal, macOS Terminal, iTerm2 |
| Shell | The program running inside the terminal that reads your command, interprets it and starts other programs. | bash, sh (dash), zsh, fish, PowerShell |
| Console | Originally the physical keyboard and screen attached to a machine. On Linux today it usually means the text-mode login you get without a graphical desktop. | The Linux virtual consoles, a server's serial console |
The terminal doesn't understand commands. It passes your typing to the shell and displays what comes back. You can see which shell you're talking to and which terminal device it's attached to:
echo $0
ps -p $$
ttybash
PID TTY TIME CMD
8791 pts/7 00:00:00 bash
/dev/pts/7$0 is the name of the running shell, $$ is its process ID, and ps -p shows that process.
pts/7 is the pseudo-terminal that the terminal window created for this session.
Because the shell is just a program, you can start a different one inside the same terminal
window. On Ubuntu, sh is a separate, smaller shell:
sh
echo $0
exit
echo $0$ echo $0
sh
$ exit
sid@devbox:~$ echo $0
bashThe prompt changed from sid@devbox:~$ to a plain $ while sh was running, and exit took
us back to Bash. The window never changed. Only the program reading our commands did.
Your login shell, the one started when you open a terminal or log in over SSH, is recorded in
the SHELL variable. /etc/shells lists every shell the system allows as a login shell:
echo $SHELL
cat /etc/shells/bin/bash
# /etc/shells: valid login shells
/bin/sh
/usr/bin/sh
/bin/bash
/usr/bin/bash
/bin/rbash
/usr/bin/rbash
/usr/bin/dash
/usr/bin/tmuxBash, sh and the shells you'll meet
A little history explains a lot of the behaviour you'll run into.
The original Unix shell that scripts were written for was the Bourne shell, sh, from Bell
Labs in 1979. Its language was later standardised by POSIX, and "sh" now means that language
rather than one particular program. Bash, the "Bourne-Again SHell", was written for the GNU
Project in 1989 as a free implementation of sh. It added many features on top: arrays, the
[[ ]] test, brace expansion, command history, tab completion and more. Every valid sh script
is (with rare exceptions) a valid Bash script. The reverse is not true.
That difference catches people out on Debian and Ubuntu, where /bin/sh is not Bash at all:
readlink -f /bin/sh/usr/bin/dashdash is a small, fast shell that implements the POSIX sh language and nothing more. A
Bash-only feature such as [[ ]] simply doesn't exist there. Run the same test in both shells
from a directory that contains access.log:
sh -c '[[ -f access.log ]] && echo "found it"'
bash -c '[[ -f access.log ]] && echo "found it"'sh: 1: [[: not found
found itThis is why a script that starts with #!/bin/sh and uses Bash syntax works on one machine and
fails on another. If you write Bash, say so in the first line with #!/usr/bin/env bash or
#!/bin/bash. We'll do that from Your First Scripts onwards.
Why macOS defaults to zsh
macOS still ships /bin/bash, but it's version 3.2, a release line that dates from 2006. Later Bash releases are licensed
under GPLv3, which Apple doesn't ship, so the system copy was frozen. Since macOS Catalina (10.15)
new user accounts get zsh as their login shell instead.
This has practical consequences:
- Bash 3.2 lacks features added in Bash 4.0 and later, such as associative arrays
(
declare -A),mapfile,${var,,}lowercase conversion and the**glob. Scripts that use them fail on a stock Mac. zshis close to Bash for everyday interactive use, but it is a different language. For example, it doesn't split unquoted variables into words by default, and its arrays start at index 1.
If you're on a Mac, Setting Up Bash and Your Terminal shows how to install a current Bash with Homebrew. Everything in this track assumes Bash 5.
The shells you'll actually run into
| Shell | Where you meet it | Notes |
|---|---|---|
bash | Default login shell on most Linux distributions, WSL, Git for Windows | What this track teaches |
sh / dash | /bin/sh on Debian and Ubuntu, Dockerfile RUN lines, cron | POSIX language only |
ash (BusyBox) | Alpine Linux containers | POSIX-ish and minimal; there's often no Bash in the image at all |
zsh | Default login shell on macOS | Mostly compatible interactively, different as a scripting language |
fish | Opt-in on developer laptops | Friendly interactive shell; its scripting syntax is not compatible with Bash |
| PowerShell | Windows, and pwsh on Linux and macOS | Object pipeline, entirely different language (see the PowerShell track) |
Anatomy of a command
Every command line follows the same pattern: a command name, then options that change how it behaves, then arguments that tell it what to work on. All three are separated by spaces. From inside the shop's project directory:
cd ~/webshop
ls -l -h logstotal 216K
-rw-r--r-- 1 sid sid 216K Nov 9 21:24 access.loglsis the command (list directory contents).-l(long format) and-h(human-readable sizes) are options.logsis the argument: the directory to list.
The shell does the splitting, not the command. Bash breaks the line into words at unquoted
spaces and hands the command a list of separate strings. You can see exactly what a command
would receive with printf, which prints each argument on its own line between brackets:
printf '[%s]\n' ls -l -h /var/log[ls]
[-l]
[-h]
[/var/log]That matters as soon as a name contains a space. Without quotes, Bash splits it into two arguments:
mkdir Q3 summary
ls
mkdir "Q3 summary"
lsQ3 summary
Q3 'Q3 summary' summaryThe first mkdir created two directories, Q3 and summary. The quoted version created one
directory with a space in its name, which ls displays in quotes so you can tell them apart. We
cover quoting fully in Variables, Quoting, and the Environment.
For now, the rule is: if a name contains spaces, put it in quotes.
Short options, long options and option values
Most GNU tools accept two spellings for each option:
- Short options are one dash and one letter:
-l,-h,-a. They can be combined, sols -l -handls -lhmean the same thing. - Long options are two dashes and a word:
--human-readable,--all. They're easier to read in scripts. GNU tools also accept any unambiguous prefix, sols --humanworks.
Some options take a value. head -n 2 shows the first two lines of a file, and so does
head --lines=2:
head -n 2 logs/access.log203.0.113.88 - - [09/Nov/2026:09:00:01 +0000] "GET / HTTP/1.1" 200 16249 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/130.0"
198.51.100.7 - - [09/Nov/2026:09:00:02 +0000] "GET /login HTTP/1.1" 200 38898 "-" "Mozilla/5.0 (X11; Linux x86_64) Firefox/131.0"Options are case-sensitive (ls -S sorts by size, ls -s prints block counts), and so are
command names. An option the command doesn't know produces an error and a hint:
ls -yls: invalid option -- 'y'
Try 'ls --help' for more information.-- means "no more options"
Anything that starts with a dash looks like an option, including file names. Suppose someone
saved a file called -n.txt:
cat -n.txt
cat -- -n.txtcat: invalid option -- '.'
Try 'cat --help' for more information.cat read -n.txt as the options -n, -., -t, -x, -t and gave up at the dot. A bare
-- tells the command that everything after it is an argument, so the second command printed the
file (it was empty) without complaint. You'll see -- again when we delete files safely in
Working with Files and Directories.
Every command reports success or failure
When a command finishes it returns an exit status: 0 means success, anything else means
something went wrong. The shell keeps the last one in $?:
ls ~/webshop/logs
echo "exit status: $?"
ls ~/webshop/nonexistent
echo "exit status: $?"access.log
exit status: 0
ls: cannot access '/home/sid/webshop/nonexistent': No such file or directory
exit status: 2You won't need this much while typing commands by hand, but scripts depend on it. It's how
&&, if and error handling decide what to do next, which is the subject of
Command Substitution, Chaining, and Exit Codes.
Your first real commands
Here are commands you'll use on any machine you've just logged into. Run them one at a time and read the output.
whoami
hostname
pwdsid
devbox
/home/sidWho you are, which machine you're on, and which directory you're in. On a production server the hostname is the most important line on the screen. Check it before you change anything.
date
uptimeMon Nov 9 21:27:05 EST 2026
21:27:05 up 16 min, 1 user, load average: 0.80, 0.63, 0.31uptime shows how long the machine has been running and its load average: roughly, how many
processes were running or waiting for the CPU, averaged over the last 1, 5 and 15 minutes.
head -n 2 /etc/os-release
uname -rPRETTY_NAME="Ubuntu 24.04.1 LTS"
NAME="Ubuntu"
6.18.54.1-microsoft-standard-WSL2The distribution and the kernel version. (The microsoft-standard-WSL2 kernel shows this
machine is Ubuntu running under WSL on Windows.)
echo "Logged in as $USER on $(hostname)"Logged in as sid on devboxecho prints its arguments. Before running it, Bash replaced $USER with the value of the USER
variable and $(hostname) with the output of the hostname command. That substitution step
happens on every command line, and much of the shell's power comes from it.
Getting help without leaving the terminal
You'll forget option letters constantly. Everyone does. What helps is knowing where to look,
and the right place depends on what kind of command you have. Ask the shell with type.
type: what kind of command is this?
type cd ls if llcd is a shell builtin
ls is aliased to `ls --color=auto'
if is a shell keyword
ll is aliased to `ls -alF'There are four kinds:
- Builtins such as
cd,echoandprintfare part of Bash itself.cdhas to be a builtin, because a separate program can't change the current directory of the shell that started it. - Keywords such as
if,forandwhileare Bash syntax. - Aliases are shortcuts defined in your startup files. Ubuntu's default
~/.bashrcdefineslland makeslsadd colour. - Files are programs on disk, found by searching the directories listed in
PATH.
type -a shows every match, in the order Bash would try them:
type -a echoecho is a shell builtin
echo is /usr/bin/echo
echo is /bin/echoThe builtin wins. The two file paths are the same program, because /bin is a link to /usr/bin
on modern Ubuntu.
help for builtins
Builtins are documented by Bash itself:
help cdcd: cd [-L|[-P [-e]] [-@]] [dir]
Change the shell working directory.
Change the current directory to DIR. The default DIR is the value of the
HOME shell variable. If DIR is "-", it is converted to $OLDPWD.
The variable CDPATH defines the search path for the directory containing
DIR. Alternative directory names in CDPATH are separated by a colon (:).
A null directory name is the same as the current directory. If DIR begins
with a slash (/), then CDPATH is not used.
[…]help with no arguments lists every builtin with a one-line synopsis.
man for programs
External programs come with manual pages:
man lsLS(1) User Commands LS(1)
NAME
ls - list directory contents
SYNOPSIS
ls [OPTION]... [FILE]...
DESCRIPTION
List information about the FILEs (the current directory by default). Sort entries alphabetically if none of
-cftuvSUX nor --sort is specified.
[…]man opens the page in a pager (usually less), so you navigate it with the keyboard:
| Key | Action |
|---|---|
Space / b | Page down / page up |
/word then Enter | Search forward for "word" |
n / N | Next / previous match |
g / G | Jump to the start / end |
q | Quit |
h | Help screen with every key |
Searching is the skill that matters. man bash is 4,912 lines long on this system. Nobody reads
it top to bottom, but /HISTSIZE takes you straight to the paragraph you need.
The (1) in LS(1) is the manual section. Section 1 is user commands, 5 is file formats,
8 is administration commands. Some names exist in more than one section. passwd is both the
command that changes your password and the file /etc/passwd:
man -aw passwd/usr/share/man/man1/passwd.1.gz
/usr/share/man/man1/openssl-cmds.1ssl.gz
/usr/share/man/man5/passwd.5.gzTo read about the file rather than the command, give the section number:
man 5 passwdPASSWD(5) File Formats and Configuration PASSWD(5)
NAME
passwd - the password file
DESCRIPTION
/etc/passwd contains one line for each user account, with seven fields delimited by colons (“:”). These fields
are:
[…]--help for a quick reminder
Most GNU programs print a compact summary with --help. It's often faster than the man page,
especially combined with grep to filter it:
ls --help | grep -i size --block-size=SIZE with -l, scale sizes by SIZE when printing them;
e.g., '--block-size=M'; see SIZE format below
-h, --human-readable with -l and -s, print sizes like 1K 234M 2G etc.
-s, --size print the allocated size of each file, in blocks
-S sort by file size, largest first
--sort=WORD sort by WORD instead of name: none (-U), size (-S),
-T, --tabsize=COLS assume tab stops at each COLS instead of 8
The SIZE argument is an integer and optional unit (example: 10K is 10*1024).Searching by topic: man -k and apropos
When you know what you want to do but not which command does it, man -k keyword (also called
apropos) searches the one-line descriptions of every manual page, and whatis prints the
description of a named command. Both read a pre-built index. On a minimal system such as a fresh
WSL install or a container image, that index has often never been built, and you get this:
apropos 'disk space'
whatis lsdisk space: nothing appropriate.
ls: nothing appropriate.The man pages are there. Only the index is missing. Build it once with sudo mandb and both
commands start working. (The test machine had no root access, so I could not run that step
here.)
For Bash itself, the complete reference is the
GNU Bash manual, which is the same text as
info bash and a more readable version of man bash.
How this learning path is organised
The Bash track is in seven sections. Each article assumes the ones before it:
| Section | Articles | You'll be able to |
|---|---|---|
| Getting Started | Introduction, Setup | Open a well-configured shell and find help |
| Files and the Filesystem | Navigating, Files and directories, Globbing, Permissions, Finding files | Move around, create, copy, delete, secure and locate files |
| Shell Fundamentals | Variables and quoting, Redirection and pipes, Exit codes and chaining | Understand what the shell does to a line before running it |
| Text Processing | grep, cut, sort, uniq, sed, awk | Answer questions about logs and data files |
| Scripting | First scripts, Loops and functions, Arrays, Error handling | Write scripts that are correct and debuggable |
| System Administration | Processes and signals, Monitoring and scheduling | Manage running programs and scheduled jobs |
| Real-World Projects | Production scripts, Backups and log reports, Deployment capstone | Build tools you'd actually run at work |
Every article ends with exercises that have tested solutions. Do them. Typing a command you've just read about teaches you much more than reading about it.
Where you'll use this
Back to the failing checkout. Here's what the first few minutes on that server look like, using only the commands from this article plus the summary line from the start. This is a real session against a sample shop log.
Confirm where you are, and that the machine isn't simply out of resources:
hostname
uptime
df -h /
free -hdevbox
21:27:05 up 16 min, 1 user, load average: 0.80, 0.63, 0.31
Filesystem Size Used Avail Use% Mounted on
/dev/sdd 1007G 4.8G 951G 1% /
total used free shared buff/cache available
Mem: 7.7Gi 1.5Gi 3.2Gi 14Mi 3.2Gi 6.2Gi
Swap: 2.0Gi 0B 2.0GiThe disk is 1% used, memory is mostly free and load is low. A full disk or a machine running out of memory would explain random failures, and both are ruled out in about ten seconds.
Look at the logs:
ls -lh ~/webshop/logs
tail -n 3 ~/webshop/logs/access.logtotal 216K
-rw-r--r-- 1 sid sid 216K Nov 9 21:24 access.log
192.0.2.99 - - [09/Nov/2026:10:17:12 +0000] "POST /api/orders HTTP/1.1" 404 9485 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/130.0"
203.0.113.88 - - [09/Nov/2026:10:17:14 +0000] "GET /static/app.js HTTP/1.1" 200 36027 "-" "kube-probe/1.31"
192.0.2.10 - - [09/Nov/2026:10:17:18 +0000] "GET /cart HTTP/1.1" 200 6754 "-" "kube-probe/1.31"Count the server errors, then look at the most recent checkout failures:
grep -c '" 50[0-9] ' ~/webshop/logs/access.log
grep '/checkout' ~/webshop/logs/access.log | grep '" 50[0-9] ' | tail -n 340
203.0.113.88 - - [09/Nov/2026:09:45:05 +0000] "POST /checkout HTTP/1.1" 502 38218 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/130.0"
203.0.113.5 - - [09/Nov/2026:09:57:23 +0000] "POST /checkout HTTP/1.1" 503 14915 "-" "curl/8.5.0"
203.0.113.88 - - [09/Nov/2026:09:58:33 +0000] "POST /checkout HTTP/1.1" 502 29062 "-" "curl/8.5.0"There were 40 server errors in total, and the checkout failures are 502 and 503. Those mean
the web server couldn't reach the application behind it, which tells you where to look next.
Combined with the summary from the start of this article (checkout has more failures than any
other page), you have a lead within a couple of minutes and without opening a single GUI.
The same pattern applies in every other place you'll meet a shell:
- Inside a container,
RUNlines in a Dockerfile are passed to/bin/sh -c. On a Debian-based image that means dash, so Bash-only syntax in aRUNline fails exactly as the[[example above did. - In a CI job, the build log shows every command and its output. Reading it is reading a shell session. See the Jenkins pipeline basics for a concrete example.
- In cron, jobs run under
/bin/shwith a minimal environment, which is why a command that works at your prompt can fail at 3 a.m. System Monitoring and Scheduling covers this.
Common mistakes
Copying the prompt along with the command
Tutorials often show commands with a leading $ to mark the prompt. Paste one of those and the
shell tries to run a command called $:
$ whoami$: command not foundThe $ (or # for root) is part of the prompt, not the command. Leave it out. Every command
block on this site is written without it for that reason.
Looking for a man page for a builtin
man cdNo manual entry for cdcd is part of Bash, not a separate program, so it has no man page of its own. Use type cd to
find out what kind of command it is, then help cd. (The builtins are also described in
man bash, under SHELL BUILTIN COMMANDS.)
Getting the case wrong
Linux command names, options and file names are case-sensitive:
Ls -lLs: command not foundls and Ls are different names. The same goes for -s and -S, and for Access.log and
access.log.
Bash syntax in an sh script
A script that starts with #!/bin/sh runs under dash on Debian and Ubuntu, and Bash features
fail with errors like [[: not found, as shown in the section on sh above. Either keep the
script to POSIX sh syntax, or change the first line to #!/usr/bin/env bash.
Summary
- The terminal is the window, the shell is the program that interprets what you type,
and you can run different shells in the same terminal.
echo $0tells you which one you're in. - Bash is a superset of the POSIX
shlanguage. On Debian and Ubuntu,/bin/shis dash, so Bash-only syntax fails in#!/bin/shscripts. - macOS ships Bash 3.2 and defaults to zsh. Install a current Bash if you want to follow along there.
- A command line is command, options, arguments, split at unquoted spaces by the shell.
Quote anything that contains spaces, and use
--to stop option parsing. - Every command returns an exit status in
$?:0for success, non-zero for failure. - Find help with
typefirst, thenhelp(builtins),man(programs),--help(quick summary) andman -k/apropos(search by topic, once the index exists). - Bash is the language of servers, containers, CI jobs and cron. Reading it is a skill you'll use even on days you don't write any.
Exercises
Use one command to find out what kind of command each of these is: pwd, printf, for, ls
and history. Then find out whether pwd also exists as a program on disk.
Show Solution
type pwd printf for ls historypwd is a shell builtin
printf is a shell builtin
for is a shell keyword
ls is aliased to `ls --color=auto'
history is a shell builtintype -a lists every match, not just the one Bash would use:
type -a pwdpwd is a shell builtin
pwd is /usr/bin/pwd
pwd is /bin/pwdThe builtin runs when you type pwd, but a standalone program also exists, for scripts and
tools that don't run inside Bash. If you just want the category, type -t prints one word per
name (builtin, keyword, alias, file or function).
You want ls to sort files by modification time, newest first, but you don't remember the
option. Find it using the built-in help and a filter, not a search engine.
Hint
ls --help prints every option. Pipe it into grep and search for a word you'd expect in the
description.
Show Solution
ls --help | grep -- ' -t' -t sort by time, newest first; see --timeThe -- after grep stops grep from treating ' -t' as one of its own options. Searching
for the word time (ls --help | grep time) works too, but it returns more lines. Inside
man ls, typing /newest and pressing Enter jumps to the same option.
Before running them, write down how many arguments printf receives in each of these commands
and what they are. Then run them to check.
printf '[%s]\n' cp "monthly report.pdf" backups/
printf '[%s]\n' cp monthly report.pdf backups/Show Solution
[cp]
[monthly report.pdf]
[backups/][cp]
[monthly]
[report.pdf]
[backups/]The format string '[%s]\n' is the first argument to printf itself. After it come three
arguments in the first command and four in the second. Without quotes, monthly report.pdf
becomes two words, so cp would look for two files that don't exist. This is the most common
source of "No such file or directory" errors in scripts that handle user-supplied file names.
Find out which program /bin/sh really is on your machine. Then show that [[ ]] works in
Bash but not in sh (if your sh is dash), using a file that exists in your home directory,
such as .bashrc.
Show Solution
readlink -f /bin/sh
cd ~
sh -c '[[ -f .bashrc ]] && echo "found it"'
bash -c '[[ -f .bashrc ]] && echo "found it"'/usr/bin/dash
sh: 1: [[: not found
found itreadlink -f follows the chain of symbolic links to the real file. On Fedora, Arch and macOS,
/bin/sh is Bash running in POSIX mode, so the first test may well print found it, which
shows why "it works on my machine" isn't proof that a script is portable. The POSIX equivalent
that works everywhere is [ -f .bashrc ].
/etc/passwd has seven colon-separated fields per line. Without searching the web, find out
what the fifth field is for. Start by finding out which manual sections document something
called passwd.
Show Solution
man -aw passwd/usr/share/man/man1/passwd.1.gz
/usr/share/man/man1/openssl-cmds.1ssl.gz
/usr/share/man/man5/passwd.5.gzSection 5 covers file formats, so that's the page you want:
man 5 passwdThe DESCRIPTION section lists the fields in order: login name, optional encrypted password,
numerical user ID, numerical group ID, user name or comment field, user home directory, and
optional user command interpreter. The fifth field is the comment field, which usually holds
the person's full name. Plain man passwd would have shown the section 1 page about the
passwd command instead.
Tested with: GNU Bash 5.2.21 on Ubuntu 24.04 (WSL2), November 2026. Every command was run as
shown, the interactive ones in a real terminal session with Ubuntu's default ~/.bashrc. The
web shop log is sample data in standard nginx format, created for these examples. sudo mandb was not run because
the test machine had no root access, and the macOS behaviour described above was not tested.
Written by The Dark Debugger
Engineer documenting the things that took me too long to learn, so they take you less time. Every Bash tutorial here is tested end to end before publishing.