Introduction to Bash

Introduction to Bash in Bash: Walk into the stores office of a large machine shop and you will find a counter, a clerk, and behind the clerk several hundred…

The Analogy: The Parts Counter at a Machine Shop

Walk into the stores office of a large machine shop and you will find a counter, a clerk, and behind the clerk several hundred metres of racking. You do not go into the racking. You write what you want on a slip -- a part number, a quantity, sometimes a bin to deliver it to -- and you push the slip across the counter. The clerk reads the slip, walks the aisles in a fixed order, comes back with the part, and stamps the slip so that you know whether the request was filled or refused.

The clerk makes nothing. That is the first thing to understand about the arrangement, and it is the first thing to understand about Bash. The clerk's entire skill is reading a short written request, resolving the vague parts of it into something exact, finding the thing that does the actual work, handing over your instructions, and reporting back. A shop with a brilliant clerk and empty racking produces nothing at all. A shop with a mediocre clerk and full racking is merely slow. Almost every program you will run from a Bash script -- grep, sed, awk, tar, curl -- lives in the racking. Bash is the counter.

The order in which the clerk walks the aisles is posted on the wall behind the counter, and it matters more than anyone expects. If two aisles both stock something called "bearing", the clerk brings back whichever one comes first on that posted list and does not mention that there was a second. Regulars learn the list. New starters do not, and they spend an afternoon insisting that the part they were handed is the wrong one, which it is not: it is exactly the part the posted order says they asked for.

The failure mode is almost never a refused slip. A refused slip is easy -- the clerk stamps NOT STOCKED, you go and find out why, and you fix the slip. The expensive failure is the slip that gets filled with the wrong thing because it was ambiguous and nobody noticed. You wrote a description with a space in the middle and the clerk read it as two separate requests. You wrote a bin number that the clerk resolved against a different list from the one in your head. The slip comes back stamped FILLED, the report you build from it looks entirely plausible, and the mistake surfaces a week later during a stock count. Every hard Bash bug in this course is a version of one sentence: the shell did exactly what the written line said, and the written line did not say what you meant.


Syntax or Core Structure

Bash reads a line, splits it into words at whitespace, treats the first word as the name of the thing to run, and passes the remaining words to it as separate arguments. printf makes that visible, because it reuses its format string once per remaining argument:

printf '[%s]\n' one two   three

Output:

[one]
[two]
[three]

Three arguments arrived, not one string, and the run of three spaces between two and three left no trace at all. Whitespace between words is a separator, not data. Getting spaces to survive into a program is the subject of the next lesson and the cause of a large fraction of all broken shell scripts.

A script is the same thing written down. Put these six lines in a file called board.sh:

#!/usr/bin/env bash
set -euo pipefail

shop="Fenwick and Sons"
jobs=3

echo "Welcome to $shop."
echo "Jobs on the board: $jobs"
echo "After the first is finished: $(( jobs - 1 )) left"

Output:

Welcome to Fenwick and Sons.
Jobs on the board: 3
After the first is finished: 2 left

Five separate ideas are packed into that file, and each one has a rule worth stating exactly.

The first line is the shebang. When the kernel is asked to execute a file it reads the first two bytes, and if they are #! it runs the named interpreter with the file as an argument instead. #!/usr/bin/env bash asks env to find bash on the current PATH, which is more portable than hard-coding a location, because Bash lives in a different directory on macOS, on Alpine, and inside a Nix build than it does on Debian.

The second line is a set of safety switches. set -e makes the script stop at the first command that fails, set -u makes an unset variable a fatal error rather than an empty string, and set -o pipefail makes a pipeline report failure when any stage in it fails rather than only the last. These three are the closest thing Bash has to a seat belt, and Module 6 is devoted to what they do and do not catch.

The assignments have no spaces around the equals sign. This is not style; shop = "Fenwick" is a command named shop with two arguments, and it will fail with shop: command not found. Assignment is a syntactic form, not an operator.

$shop and $jobs are parameter expansions: the shell replaces the name with the value before the command runs, so echo never sees a variable at all -- it receives finished text. $(( jobs - 1 )) is an arithmetic expansion, and inside those double parentheses you do not write the dollar sign at all, because the whole region is already understood as arithmetic.

Every command also leaves behind a number. Not output -- a separate one-byte verdict called the exit status, readable as $? until the next command overwrites it:

echo "one two three" | grep -q two
echo "found two, status $?"
echo "one two three" | grep -q four
echo "looked for four, status $?"

Output:

found two, status 0
looked for four, status 1

Zero means success and any non-zero value means some kind of failure, which is backwards from the convention in most languages and is the reason if in Bash tests a command, not a boolean. That single fact drives the whole control-flow module, and it is why the grep -q above needed no == true anywhere.


Technical Depth: How One Line Becomes a Running Program

The nine rewrites, in order

Before any program starts, Bash rewrites the line you typed. It does so in a fixed sequence, and the sequence -- not the left-to-right position of the characters -- decides the outcome.

OrderStageWritten asBecomes
1brace expansion{a,b}-{1,2}four words: a-1 a-2 b-1 b-2
2tilde expansion~ at the start of a wordthe value of HOME
3parameter expansion$namethe value stored under that name
4command substitution$(printf ab)the standard output of that command, trailing newlines removed
5arithmetic expansion$(( 3 * 4 ))the text 12
6process substitution<(sort data)the name of a pipe that yields sorted output
7word splittingany unquoted result of stages 3 to 6split into words at every character in IFS
8pathname expansion*.txtthe matching filenames in sorted order, or the pattern itself if nothing matches
9quote removal"a b"the two-word text a b, now a single argument

The ordering is testable, and the test is worth running once by hand because it explains a bug you will otherwise meet at a bad moment:

#!/usr/bin/env bash
n=2
echo file{1..3}.txt
echo "file{1..$n}.txt"
echo file{1..$n}.txt

Output:

file1.txt file2.txt file3.txt
file{1..2}.txt
file{1..2}.txt

The second and third lines print the same thing for completely different reasons. Line two is inside double quotes, so brace expansion never applies and only the parameter expands. Line three is unquoted, so brace expansion is attempted first -- at that moment the text is still {1..$n}, which is not a numeric range, so the brace is left alone as literal text -- and only afterwards does $n become 2. By then the brace stage is over and will not be revisited. This is why a numeric range in Bash can never be driven by a variable, and why seq or a C-style for loop is the correct tool when the bound is computed.

Stage 7 is the one that costs people money. Compare:

#!/usr/bin/env bash
file="two words.txt"
printf '[%s]\n' $file
printf '[%s]\n' "$file"

Output:

[two]
[words.txt]
[two words.txt]

Nothing about $file changed between those two lines. The quotes did not change the value; they suppressed stage 7, so the expanded value stayed one word. Unquoted expansions are re-split, and that is how a filename with a space in it becomes two arguments and a rm command deletes the wrong thing.

What the first word can actually be

"Run the program named by the first word" is a simplification. Bash resolves the first word against five kinds of thing, in this order, and stops at the first match.

OrderKindWhat it isReported by type -t as
1reserved wordsyntax such as if, while, functionkeyword
2aliasa text substitution, expanded only in interactive shells by defaultalias
3functionshell code defined in this shell or a sourced filefunction
4builtincode compiled into Bash itself, such as cd or echobuiltin
5external filean executable found by walking PATH left to rightfile

type -t answers the question directly, which makes it the fastest way to explain surprising behaviour:

#!/usr/bin/env bash
greet() { echo "hello"; }
echo "if     -> $(type -t if)"
echo "echo   -> $(type -t echo)"
echo "grep   -> $(type -t grep)"
echo "greet  -> $(type -t greet)"
echo "nosuch -> $(type -t nosuch || echo none)"

Output:

if     -> keyword
echo   -> builtin
grep   -> file
greet  -> function
nosuch -> none

Two consequences follow. First, a function silently wins over a builtin of the same name, which is a legitimate technique and an excellent way to confuse a colleague. builtin and command exist to bypass the earlier stages:

#!/usr/bin/env bash
echo() { printf 'via function: %s\n' "$*"; }
echo hello
builtin echo hello
unset -f echo
echo hello

Output:

via function: hello
hello
hello

Second, aliases are not expanded when a script runs. An alias defined in an interactive session is invisible to every script that session starts, which is why alias rm='rm -i' does not protect your scripts and should never be relied on as a safety measure.

The posted aisle order

Stage 5 above is the PATH search, and PATH is a colon-separated list scanned strictly left to right, first match wins. Two directories can hold the same command name, and only the order decides which one runs:

#!/usr/bin/env bash
mkdir -p aisle1 aisle2
printf '#!/usr/bin/env bash\necho "aisle one"\n' > aisle1/bearing
printf '#!/usr/bin/env bash\necho "aisle two"\n' > aisle2/bearing
chmod +x aisle1/bearing aisle2/bearing

PATH="aisle1:aisle2:$PATH" bearing
PATH="aisle2:aisle1:$PATH" bearing

Output:

aisle one
aisle two

The same word, the same directories, a different verdict, and no warning that a second candidate existed. Note also the form of those last two lines: NAME=value command sets a variable for that one command only and does not touch the current shell's PATH.

Bash also caches the resolved location of each external command in a hash table, so a newly installed program can appear absent until hash -r clears the cache. That cache is per shell, which is why the program is found in a new terminal and not in the one you have had open all afternoon.

The verdict codes

Exit status is one byte, so values wrap at 256, and the useful values are conventions rather than rules the shell enforces.

StatusMeaningTypical source
0successevery program that finished its job
1general failuregrep found nothing, test was false
2usage errora builtin called with bad syntax, many GNU tools on a bad option
126found but could not be executedmissing execute permission, or a directory
127command not founda typo, or a PATH that does not contain the tool
128 plus Nkilled by signal N130 is SIGINT from Ctrl-C, 137 is SIGKILL
255out of range or a program-specific catastropheexit -1 wraps to 255

Only 0, 1, 2, 126, 127 and the signal range are standardised. Everything from 3 to 125 belongs to the program, so curl uses dozens of them and rsync publishes a table of its own.

#!/usr/bin/env bash
nosuchcommand 2>/dev/null
echo "not found -> $?"

Output:

not found -> 127

Which startup files run, and when none of them do

This table explains more support tickets than any other fact in the module.

InvocationFiles read
interactive login shellthe system profile, then the first one of the user's bash_profile, bash_login or profile that exists
interactive non-login shellthe system bashrc where the distribution provides one, then the user's bashrc
a script, or any non-interactive shellnone at all, unless BASH_ENV names a file
invoked under the name shPOSIX mode, and the bashrc files are skipped

The third row is the answer to "it works in my terminal but not in cron". Cron runs a non-interactive shell with a minimal environment, so the PATH edits and aliases in your bashrc simply do not exist. The fix is never to source your bashrc from the script; it is to set what the script needs, explicitly, at the top of the script.


Real World Example: Valuing a Parts List Without Floating Point

A stores clerk's actual job is arithmetic on a list, so here is that program. It takes a fixed parts list, prints an aligned report, and totals it. Everything in it is from this lesson plus one construct from later ones, and it runs unchanged on any Bash from version 4 onward.

#!/usr/bin/env bash
set -euo pipefail

# One record per part: name, quantity, unit price in whole cents.
parts=("bearing-6203:24:375" "belt-a38:6:1120" "seal-kit-90:12:705" "grease-2kg:3:1840")

money() {
  printf '%d.%02d' "$(( $1 / 100 ))" "$(( $1 % 100 ))"
}

printf '%-14s %4s %9s %10s\n' "PART" "QTY" "UNIT" "VALUE"
printf '%-14s %4s %9s %10s\n' "--------------" "----" "---------" "----------"

total=0
for row in "${parts[@]}"; do
  name=${row%%:*}
  rest=${row#*:}
  qty=${rest%%:*}
  cents=${rest##*:}
  value=$(( qty * cents ))
  total=$(( total + value ))
  printf '%-14s %4d %9s %10s\n' "$name" "$qty" "$(money "$cents")" "$(money "$value")"
done

printf '%-14s %4s %9s %10s\n' "TOTAL" "" "" "$(money "$total")"
echo "rows: ${#parts[@]}  total in cents: $total"

Output:

PART            QTY      UNIT      VALUE
-------------- ---- --------- ----------
bearing-6203     24      3.75      90.00
belt-a38          6     11.20      67.20
seal-kit-90      12      7.05      84.60
grease-2kg        3     18.40      55.20
TOTAL                             297.00
rows: 4  total in cents: 29700

The four expansions inside the loop are the record splitter, and they are worth learning as a set because they appear in every Bash script that reads structured text. ${row%%:*} removes the longest match of :* from the end, leaving everything before the first colon: the name. ${row#*:} removes the shortest match of *: from the front, leaving everything after the first colon. Applying the same pair to what is left peels off the quantity, and ${rest##*:} removes the longest front match to leave the final field. The mnemonic is that # points at the start of a line on your keyboard's number row and % sits near the end, and that doubling the symbol makes it greedy.

Prices are stored in whole cents on purpose, because Bash arithmetic is integer-only and will not pretend otherwise. $(( 3.75 * 24 )) does not round or truncate; it fails with syntax error: invalid arithmetic operator and takes the script down with it. That is genuinely the right default for a shell -- silent rounding of money is worse than a stopped script -- but it means every currency calculation in Bash is either scaled to the smallest unit, as here, or handed to awk, bc or python3. The money helper exists only to put the decimal point back for display, dividing by 100 for the whole part and taking the remainder for the fractional part.

The columns line up because printf was given field widths, and this is the one formatting habit worth forming on day one. %-14s is a left-aligned string in a field of fourteen characters, %4d is a right-aligned integer in four, and the same format string is reused for the header, the rule and the total so that the four columns cannot drift apart. echo cannot do any of this: it takes no format, it interprets backslashes differently on different systems, and it adds exactly one newline. Any output a human or another program will parse should come from printf.

Now the honest part, because this program has one bug and several limits. The bug is in money: it is written for non-negative values only, and money -375 prints -3.-75 rather than -3.75, because the sign is applied to the quotient and the remainder independently. A parts list is not obviously a place for negative numbers until the day someone adds a credit note or a stock correction, and then the report prints something that is not a number at all while exiting 0 -- the worst of both worlds. The limits are cheaper to state: the record format has no escaping, so a part name containing a colon shifts every field to the right of it and the script dies inside the arithmetic rather than reporting a bad record; there is no currency anywhere, so the report cannot be mixed across suppliers; the data is embedded in the script, so updating stock means editing code; and nothing cross-checks the total against an independently known figure, so a row silently dropped from the array simply produces a smaller, entirely plausible number. Every one of those is fixed in later modules -- validation in Module 2, real record parsing in Module 4, and reading data from files in Module 5 -- but the fix that matters most is the habit of asking, of every script you write, "what does this print when the input is not what I imagined?"


Common Mistakes

  1. Putting spaces around the equals sign. count = 3 is not an assignment; it is an attempt to run a command called count with the arguments = and 3, and it fails with count: command not found. Assignment is a syntactic form recognised only when the name, the equals sign and the value touch.
  2. Leaving expansions unquoted. rm $file with a filename containing a space deletes two wrong things. Quoting is not decoration; it suppresses word splitting and glob expansion, and the default for every expansion should be to quote it.
  3. Running a Bash script with sh. sh script.sh ignores the shebang entirely and runs the file under whatever sh is on that machine, which on Debian and Ubuntu is Dash. Arrays, [[ ]], local and $(( )) behave differently or not at all, and the errors point at lines that are perfectly correct Bash.
  4. Assuming a script inherits your interactive setup. Scripts read no startup files, so the PATH edits, functions and aliases in your bashrc do not exist inside them. Anything the script needs must be set by the script.
  5. Using echo for structured output. Whether echo -n suppresses the newline and whether echo "a\tb" produces a tab both depend on which echo you got and which options are set. printf is specified, portable and takes a format string, which is why every example in this course that formats anything uses it.
  6. Reading exit status as a boolean. In Bash, 0 is success and non-zero is failure, so a command that "returns true" returns zero. Writing if [ $? == 1 ] to mean success inverts the logic and looks correct in review.
  7. Checking $? one command too late. $? holds the status of the most recent command, and echo is a command. Any line between the thing you care about and the test overwrites it, so capture it immediately with something like status=$? if you cannot test it straight away.
  8. Expecting decimals from $(( )). Bash arithmetic is integer-only. $(( 7 / 2 )) is 3 with no warning, and $(( 1.5 + 1 )) is a fatal syntax error. Scale to the smallest unit, or delegate to awk or bc.
  9. Saving the script with Windows line endings. A trailing carriage return makes the shebang read as /usr/bin/env bash\r, which does not exist, and the error is the baffling bad interpreter: No such file or directory even though the interpreter is plainly there. Configure the editor for LF, and reach for file or cat -A when a script that looks perfect will not start.

Best Practices

  • Open every script with the same two lines. #!/usr/bin/env bash finds Bash wherever it lives, and set -euo pipefail turns three classes of silent failure into stops. Add them before you write the first real line, not after the first incident.
  • Quote by default and treat an unquoted expansion as a decision. The rare cases where you genuinely want splitting -- deliberately splitting a list, or letting a glob expand -- deserve a comment saying so, because the reviewer cannot otherwise tell intent from omission.
  • Use printf for output and give it field widths. Aligned columns from a reused format string cannot drift, and the same habit makes output that a later script can parse.
  • Declare the environment the script depends on. Set PATH, set LC_ALL where sorting or number formatting matters, and never assume that whatever ran the script gave you a login shell.
  • Ask the shell what will actually run. type -t name tells you keyword, alias, function, builtin or file, and command -v name gives the resolved target. Both are faster than guessing why the wrong version executed.
  • Keep money and other exact quantities in integers. Store the smallest unit, convert only for display, and hand genuine floating-point work to awk rather than reaching for a Bash workaround.
  • Make the script executable and commit it with LF endings. chmod +x plus a .gitattributes line marking shell scripts as text with LF endings prevents the entire category of shebang failures on mixed-platform teams.
  • Run ShellCheck on every script, and read the wiki page it cites. It catches the unquoted expansion, the $? clobber and the sh incompatibility for free, and each finding has an explanatory page that is better than most tutorials.

Practice Exercises

  1. Repeat the aisle experiment. Build the two directories and two bearing scripts from the PATH section, then work out and confirm what happens when you place a function called bearing in the same shell. Report which of the three definitions wins, and which builtin lets you deliberately reach the file version instead.
  2. Fix the money bug. Rewrite money so that money -375 prints -3.75, money 5 prints 0.05 and money 0 prints 0.00. Do it with integer arithmetic only, no awk and no bc, and test all four values plus money -5.
  3. Prove the startup-file table. Add a line to your bashrc that defines a function, open a new terminal and confirm the function exists, then call it from a script file run with bash script.sh. Explain the result in two sentences, then make the script work without sourcing your bashrc.
  4. Survey the verdict codes. Write a script that provokes and reports statuses 0, 1, 2 and 127, each in a separate command whose stderr you discard, and print a two-column table of the code and what caused it. Then add a fifth case that exits with 130 without pressing Ctrl-C, and say why 130 rather than 2 is the conventional value for an interrupt.