Course contents · Lesson 16 of 19

Bash Scripting Basics: Your First Shell Script

Shell Scripting · Lesson 16 of 19 · 11 min Hands-on

Every morning you log in to a server and type the same five commands to check it. One day you skip a step, and nobody notices for a week. This lesson covers Bash scripting basics: write the commands into a file once, run it, give it input, check that it worked, and stop it when something fails.

Your first script: hello.sh

A shell script is a plain text file of commands. Bash, the shell from lesson 4, reads it from top to bottom and runs each line as if you had typed it.

In the lab shell (the try-it below opens it), create the file with nano hello.sh. nano is a small text editor: type the lines, save with Ctrl+O and Enter, and leave with Ctrl+X.

#!/usr/bin/env bash
# hello.sh: my first script
echo "Hello from a script"
whoami
pwd

The first line is the shebang: #!, then the program that should run the file. It must be the very first line. When you run the script, the kernel, the core of the operating system (lesson 2), reads it and starts that program with the script's path.

/usr/bin/env bash asks a small program, env, to find bash in your PATH: the list of folders the shell searches for a command's name. So the script works in whichever PATH folder bash lives. Below it, whoami prints your user name and pwd your folder.

Make it runnable: chmod +x and ./

A new file has no execute permission, the x in ls -l (lesson 6), and the kernel runs no file without one, not even for root. Below, $ stands for the prompt: type what follows it; the other lines are output.

$ ./hello.sh
bash: ./hello.sh: Permission denied
$ chmod +x hello.sh
$ ./hello.sh
Hello from a script
root
/lab

chmod prints nothing, and ls -l hello.sh now starts with -rwxr-xr-x. The lab shell runs as root in /lab; your own terminal shows your name and folder.

Why ./? A name without a slash is looked up only in the PATH folders, which do not include the current one, so plain hello.sh gets bash: hello.sh: command not found. ./ names the file in the current folder (lesson 5).

bash hello.sh also works: bash opens the file itself, so it needs only read permission. Avoid sh hello.sh: on Debian and Ubuntu, sh is dash, which lacks some Bash features.

Arguments and exit codes

Now make it greet someone. Replace hello.sh with this version, labelled part by part in the diagram:

#!/usr/bin/env bash
# hello.sh: greet someone by name
# Usage: ./hello.sh NAME
set -euo pipefail

if [[ $# -eq 0 ]]; then
  echo "Usage: $0 NAME" >&2
  exit 1
fi

echo "Hello, $1"

The words after a script's name are its arguments. Inside it, $1 is the first, $2 the second, $# their number and $0 the script's name as you typed it. "$@", in double quotes, means all of them, each kept as a separate word.

The if block is a guard: when $# is 0, it prints how to use the script, and exit 1 ends the script with exit code 1 (lesson 17 explains if). In the diagram, notice that the work comes last.

The script hello.sh in an editor window with line numbers, each part labelled. Line 1, #!/usr/bin/env bash, is the shebang: which program runs the file. Lines 2 and 3 are comments, which bash skips. Line 4, set -euo pipefail, holds the safety settings: stop on errors, unset names and failed pipes. Lines 6 to 9 are a guard: with no argument, print a usage message to stderr and stop with exit code 1. Line 11, echo Hello, $1, is the command, where $1 is the first argument. A footer says a script with no exit line at the end exits with its last command's code, 0 here
Read a script top to bottom: interpreter, purpose, safety net, guard, then the work.

Every command ends with an exit code, also called its exit status (lesson 12): a number from 0 to 255. 0 means success and anything else failure; each program's manual lists its codes. Bash uses 127 for "command not found" and 126 for a file it found but could not run. $? holds the last code:

$ ./hello.sh Asha
Hello, Asha
$ echo $?
0
$ ./hello.sh
Usage: ./hello.sh NAME
$ echo $?
1

Read $? straight away, since every command, even echo, replaces it. A script without an exit line ends with its last command's code, echo's 0 here. Codes also chain commands: a && b runs b only if a succeeded, and a || b only if a failed.

The diagram sums up the loop: chmod changes nothing you can read in the file, yet without it step 3 is refused.

Four steps, each with what you type on the left and what you see on the right. Step 1, write the script with nano hello.sh: ls -l shows -rw-r--r--, a text file with no x yet. Step 2, make it runnable with chmod +x hello.sh: chmod prints nothing, and ls -l now shows -rwxr-xr-x. Step 3, run it with ./hello.sh Asha: it prints Hello, Asha, and ./ means the file in this folder. Step 4, check how it ended with echo $?: it prints 0, which means success, while 1 to 255 mean failure. A warning says that if you skip step 2, you get bash: ./hello.sh: Permission denied
After step 1 the text never changes; chmod only adds the permission step 3 needs.

Comments, quoting and where output goes

Bash ignores everything from a # at the start of a word to the end of the line: a comment, a note for people, as on lines 2 and 3. To bash, even the shebang is a comment; only the kernel reads it.

echo prints its arguments with one space between them. Quotes decide what counts as one argument: double quotes keep spaces but still replace $1 and other $ names with their values; single quotes keep every character, so echo 'Hello, $1' prints Hello, $1.

The lab's args.sh shows why this matters. It prints its name, first argument and count, then runs printf '[%s]\n' "$@", which puts each argument in brackets on its own line:

$ bash args.sh "Asha Rao" Ravi
Script: args.sh
First argument: Asha Rao
Number of arguments: 2
[Asha Rao]
[Ravi]

The quotes made Asha Rao one argument, and "$@" kept it whole. Without them, the shell would split it at the space, and the count would be 3.

echo writes to stdout, the normal output stream (lesson 8). Usage and error messages belong on stderr, so the guard adds >&2, short for 1>&2: send this echo's stdout where stream 2 goes. So ./hello.sh > greeting.txt, with no name, still shows the usage message on screen and leaves greeting.txt empty.

Safer scripts: set -euo pipefail

By default, bash carries on after a failed command: if a cd fails, the next lines run in the wrong folder, and the script may still end with code 0. The lab's steps.sh prints Step 1, runs cat on a file that does not exist, then prints Step 2:

$ bash steps.sh
Step 1
cat: missing.txt: No such file or directory
$ echo $?
1

Its set -euo pipefail line stopped it at the failed cat, with cat's code, 1. Put a # in front of that line with nano and run it again: Step 2 appears, and echo $? prints 0, because the last command worked. In the flowchart, follow the no branch when set -e is off.

Flowchart. Run the next command; it ends with an exit code. Is the exit code 0? If yes, success: go on to the next line. If no, is set -e on? If no, the script carries on anyway to the next line, and the failure is easy to miss. If yes, the script stops at once and exits with the failed command's code. A side note says set -e does not stop the script for a command tested by if, or on the left side of && or ||. Three chips at the bottom: -e, stop at a failed command; -u, an unset name is an error; -o pipefail, any failed part fails the pipe
Without set -e, a failed command leads back to the next line, just like a success.

The set line turns on three bash settings:

  • -e (errexit): stop at the first command that fails, with its code. Failures tested on purpose do not count: the command after if, or one on the left of && or ||.
  • -u (nounset): a name that was never set is an error, so a missing argument or a typo stops the script with an unbound variable error instead of becoming empty text. $# is always set, so the guard can check it.
  • -o pipefail: a pipeline fails if any command in it fails, not only the last.

In grep ERROR app.log | wc -l with app.log missing, grep fails but wc succeeds, so the pipeline looks fine; with pipefail, -e stops the script. But grep also returns 1 for no match, which then counts as a failure.

Check yourself

bash hello.sh works, but ./hello.sh says Permission denied. Why the difference?

bash hello.sh has bash open the file, which needs only read permission. ./hello.sh asks the kernel to execute it, which needs the x that chmod +x adds.

A script without set -e prints an error halfway through, yet echo $? then prints 0. Why, and what would set -e change?

A script's exit code is its last command's, and the last line worked, so the failure is lost. set -e would stop the script at the failed command, with that command's non-zero code.

You type ./hello.sh Asha Rao without quotes. What does it print, and what is $#?

Hello, Asha, with $# at 2: the shell split the words at the space, so $1 is Asha and $2 is Rao. Quote "Asha Rao" to pass one argument.