Skip to content

16 min read

Bash scripts: how to write your first script

In one sentence: A shell script is a text file with commands that the shell runs one after another. With a first line that says who reads it and permission to run, it becomes one more command, one that always does the same thing.

What you will learn

  • Create a script with its shebang, give it permission to run with chmod +x and run it.
  • Use variables, arguments ($1, $#, $@), if, test and for.
  • Make a script stop at the first error with set -euo pipefail and report through its exit code whether it went well.
  • Decide when a task is no longer a job for bash and is better written in Node or Python.

Before you start, read: 07-environment-variables.md

Imagine you have an online shop on a server. Every night, before touching anything, you check that the server is answering and you copy the website’s folder with the date in its name. It’s several commands, and you type them from memory.

One night you get a letter wrong and the backup doesn’t happen. You don’t notice, because the error went by among other lines. Three weeks later you need that backup, and it doesn’t exist.

The solution is to write the commands once, in a file, and run the file: a ScriptA text file with commands that the shell runs one after another, as if you typed them. It’s for repeating a task the same way every time.Go to definition. And a well-made one stops if something fails and tells you whether it went well.

The analogy

Think of a recipe written for someone else to follow. Everything has to be on the paper: every step, in order.

It starts by saying who it’s for (“for the bread machine”): that’s the first line of the script. It has blanks you fill in when you use it (“for ___ people”): those are the arguments. It can say “if there are no eggs, stop.” And whoever follows it leaves you a note: “it turned out fine” or “it burned.”

Where the analogy breaks down

  • Whoever follows a script doesn’t improvise: if a blank is left empty, they carry on with the blank empty.
  • A sensible cook stops if a step goes wrong. The shell, by default, carries on with the next one: it only stops if you ask it to.
  • The final note isn’t a sentence but a number: 0 if everything went well, and another one if something failed.

This is a complete script, hello.sh:

hello.sh
#!/usr/bin/env bash
# My first script: says hello and gives today's date.
echo "Hello from a script"
echo "Today is $(date +%Y-%m-%d)"
echo "Run by bash $BASH_VERSION"

When you run it, the ShellThe program that reads what you type in the terminal, interprets it and runs it. The most used are bash, the one on almost every Linux, and zsh, the one on macOS.Go to definition reads the lines from top to bottom and does with each one exactly what it would do if you typed it yourself.

  • Lines that start with # are comments: the shell doesn’t run them. They’re for whoever reads it.
  • $(…) runs the command inside and puts its output in that spot. date +%Y-%m-%d writes the date as year, month and day: 2026-10-12.
  • $BASH_VERSION is a variable that bash fills in with its version.

The first line, #!/usr/bin/env bash, is the ShebangThe first line of a script, the one that starts with #!. It says which program has to read the rest of the file; for example, #!/usr/bin/env bash asks bash, one of the most used shells, to read it.Go to definition (from hash, #, and bang, !). When you run a file, the system looks at its first two characters. If they’re #!, it hands the file to the program named in the rest of the line.

/usr/bin/env bash means “look for bash in the PATH folders,” which you saw in lesson 7, “Environment variables”. That way it works even if bash is in a different folder on each system.

In this course, scripts are always bash scripts, also on the Mac, where your shell is zsh:

  • bash is on almost every Linux server. What you write on your Mac works the same on the server.
  • The shebang is in charge, not your shell. Even if you launch it from zsh, bash reads it. That’s why hello.sh prints the bash version: on a Mac, a 3.2 from 2006. This lesson works with it and with version 5 on Linux.

You can hand the script to bash, bash hello.sh, or run it like any other command, ./hello.sh. For the second, the file needs permission to run (the execute permission), an x you can see in ls -l. A freshly created file doesn’t have it:

$ ls -l hello.sh
-rw-r--r--@ 1 ana staff 168 Oct 12 15:30 hello.sh
$ ./hello.sh
zsh: permission denied: ./hello.sh
$ chmod +x hello.sh
$ ./hello.sh
Hello from a script
Today is 2026-10-12
Run by bash 3.2.57(1)-release

chmod +x hello.sh gives it the x: the letters at the beginning go from rw-r--r-- to rwxr-xr-x, as in lesson 4, “Users and permissions”. Your date will be today’s. On Linux and WSL, the error ends in ./hello.sh: Permission denied, the @ doesn’t show up (it’s a macOS-only mark) and the version is a 5, like 5.2.21(1)-release.

And why ./hello.sh and not hello.sh? As you saw in lesson 7, the shell only looks for commands in the PATH folders, and your practice folder isn’t one of them: without ./ (“here”), it answers command not found.

You already created variables in lesson 7: a name that holds a value, with no spaces around the =, read with a $ in front. In a script they work the same:

Ventana de terminal
folder="backups"
today="$(date +%Y-%m-%d)"
echo "Saving today's backup, $today, in $folder"

When you read one, always put it in double quotes: "$folder". If the value has a space, like my notes.txt, without quotes the shell cuts it in two, my and notes.txt: two names that don’t exist.

Arguments are the recipe’s blanks. Whatever you type after the script’s name reaches it in some special variables:

Variable What it holds
$1, $2… The first argument, the second…
$# How many arguments there are
"$@" All of them, each one separately
$0 How the script itself was called

This script, greet.sh, uses all of them (the for is coming up):

greet.sh
#!/usr/bin/env bash
echo "My name is $0 and I got $# arguments."
echo "The first one is: $1"
for name in "$@"; do
echo "Hello, $name"
done

If you run it with ./greet.sh Ana "Mary Smith", it answers:

My name is ./greet.sh and I got 2 arguments.
The first one is: Ana
Hello, Ana
Hello, Mary Smith

Notice the 2: the quotes make "Mary Smith" a single argument. And "$@", in quotes, keeps it whole; without them, you’d get Hello, Mary and Hello, Smith.

if and test: doing something only if a condition holds

Section titled “if and test: doing something only if a condition holds”

if runs a command and checks whether it went well. If it did, it does what comes after then; if not, what comes after else. fi (if backwards) closes the block:

Ventana de terminal
if [ -d "$folder" ]; then
echo "The folder $folder exists"
else
echo "I can't find the folder $folder"
fi

The command that usually goes after if is [, which is also called test. Yes: [ is a command, and that’s why it needs spaces on both sides. It checks a condition and finishes successfully if it holds:

Condition It holds if…
[ -f "$x" ] $x is a file that exists
[ -d "$x" ] $x is a folder that exists
[ -e "$x" ] $x exists, whatever it is
[ "$a" = "$b" ] the two texts are equal (!=, different)
[ "$n" -eq 3 ] the number $n equals 3 (-ne not equal, -gt greater, -lt less)
[ ! -d "$x" ] the opposite: ! flips any condition

Any command can go after if, not just [. if nc -z 127.0.0.1 8080; then means “if nc manages to connect to port 8080.” You’ll use it in “Try it.”

for: repeating the same thing with each item

Section titled “for: repeating the same thing with each item”

for repeats a block with each item in a list. On each round, the variable holds the next one:

Ventana de terminal
for port in 22 80 443; do
echo "Checking port $port"
done

The list can be one you write, all the arguments ("$@") or the files that match a pattern, like *.log.

To count, bash has $(( )): failures=$((failures + 1)) adds one to failures. It only knows whole numbers: $(( 7 / 2 )) gives 3, not 3.5.

As you saw in lesson 3, every program finishes with a number, its Exit codeThe number a program leaves when it finishes. 0 means it went well, and any other, from 1 to 255, that something failed. The shell keeps it in $?, and scripts check it to decide whether to go on.Go to definition: 0 if everything went well, and 1 to 255 if something failed.

A script chooses its own with exit: exit 0 finishes successfully, and exit 1, with an error. If you don’t write exit, the code is the last command’s. By convention, 1 is the general error and 2, “you called me wrong.” The shell uses 126 if the permission to run is missing and 127 if it can’t find the command.

It’s what the programs that monitor servers, deploy or run tests look at: they don’t read the screen, only the number. Error messages, on top of that, are sent to the error output (output 2 from lesson 3) by putting >&2 at the end of the echo.

set -euo pipefail: stopping at the first error

Section titled “set -euo pipefail: stopping at the first error”

This script tries to go into a folder that doesn’t exist:

no-brakes.sh
#!/usr/bin/env bash
cd /folder-that-does-not-exist
echo "Moving on, in $(pwd)"
./no-brakes.sh: line 2: cd: /folder-that-does-not-exist: No such file or directory
Moving on, in /Users/ana/backend-course/phase-1

cd fails, bash prints the error and carries on with the next line, in the wrong folder (on Linux, /home/ana/…). If that line deleted files, it would delete the ones in your practice folder. And the script finishes with code 0, because the last echo worked.

That’s why the scripts in this course have, right after the shebang, set -euo pipefail. They’re three brakes:

  • -e: if a command fails, the script ends there, with that command’s code. With it, no-brakes.sh stops after the cd error, with code 1.
  • -u: using a variable that doesn’t exist is an error. Without it, a typo like $foldr turns into empty text, and "$foldr"/* becomes /*: everything that hangs from the root. With -u, bash stops and prints foldr: unbound variable (“variable not defined”).
  • -o pipefail: a pipe (|, from lesson 3) fails if any of its parts fails. Without it, grep 404 missing.log | wc -l finishes with code 0, because wc worked, even though grep couldn’t find the file.

The danger of an empty variable isn’t exaggerated. In 2015, Steam’s script for Linux had the line rm -rf "$STEAMROOT/"*. For a user who had moved the Steam folder, STEAMROOT ended up empty, and the command deleted all their files, even the ones on their backup drive (the report on GitHub).

The brakes don’t stop everything. -u doesn’t trigger with a variable that exists but is empty, like that STEAMROOT. And -e doesn’t act in the condition of an if, or before && or ||, because there the failure is part of the plan. Whatever really matters, check it yourself with if, as the scripts in “Try it” do.

bash is perfect for chaining programs: launching nc, tar or curl, checking whether they went well and deciding the next step. For everything else it falls short:

Sign Why bash struggles
It goes past about 100 lines It’s hard to read and change without breaking something
It does math with decimals $(( )) only knows whole numbers
It works with structured data, like JSON bash only understands text and simple lists

Google’s style guide for shell scripts sets the limit at 100 lines. The rule of thumb: if the script mostly calls other programs, bash; if it mostly works with data, Node (from Phase 3) or Python.

The goal: write two scripts that are genuinely useful on a server. One tells you whether there’s a ServerA program that waits for requests and answers them. By extension, the computer it runs on is also called a server.Go to definition listening on a PortA number, from 0 to 65535, that says which program on a computer a connection is for. The computer has an address; each listening program has its port.Go to definition; the other saves backups of a folder with the date in the name. It all happens in your terminal, inside ~/backend-course/phase-1.

The outputs are from a Mac; on Linux and WSL they’re the same. Create each file with nano, as in lesson 2: nano is-listening.sh, paste the content, save with Ctrl + O and Enter, and exit with Ctrl + X.

When a server doesn’t answer, the first thing is to find out whether its program is listening. This script checks it on the ports you give it, on your computer, with nc -z: the -z makes nc only try to connect, without sending anything.

is-listening.sh
#!/usr/bin/env bash
# Checks whether a server is listening on one or more ports of this computer.
# Usage: ./is-listening.sh PORT [PORT...]
set -euo pipefail
if [ "$#" -eq 0 ]; then
echo "Usage: $0 PORT [PORT...]" >&2
exit 2
fi
host="127.0.0.1"
failures=0
for port in "$@"; do
if nc -z "$host" "$port" >/dev/null 2>&1; then
echo "OK $host:$port is listening"
else
echo "FAIL $host:$port is not answering"
failures=$((failures + 1))
fi
done
if [ "$failures" -gt 0 ]; then
exit 1
fi

Read it before running it. If you don’t give it any port, it explains how to use it and finishes with 2. Otherwise, it tries each port, counts the ones that fail and, if any failed, finishes with 1.

It uses 127.0.0.1 and not localhost, because on a Mac nc -l only listens on IPv4 (Phase 0, lesson 5).

1. Give it permission and call it wrong on purpose

Ventana de terminal
chmod +x is-listening.sh
./is-listening.sh
echo $?

What you will see:

Usage: ./is-listening.sh PORT [PORT...]
2

Notice the 2 on the last line. If you get permission denied, the chmod +x is missing; if you get command not found, you left out the ./.

Now you need a server. Open another terminal window and start one with nc -l 8080, as in lesson 5, “Processes and signals”. That terminal stays still, listening. Go back to the first one:

2. Check port 8080 twice

Ventana de terminal
./is-listening.sh 8080
./is-listening.sh 8080

What you will see:

OK 127.0.0.1:8080 is listening
FAIL 127.0.0.1:8080 is not answering

The first time, fine; the second, it fails. Look at the other terminal: nc has finished. nc -l handles a single connection and closes, and that connection was your first check.

In the other terminal, start a server that can take several connections: nc -lk 8080. The -k (for keep) makes it keep listening after each one. Go back to the first one:

3. Several ports and the exit code

Ventana de terminal
./is-listening.sh 8080 3000
echo $?
./is-listening.sh 8080 && echo "All up and running"

What you will see:

OK 127.0.0.1:8080 is listening
FAIL 127.0.0.1:3000 is not answering
1
OK 127.0.0.1:8080 is listening
All up and running

Nobody is listening on 3000, so the script finishes with 1. With 8080 alone, it finishes with 0, and && runs the echo. If 3000 comes out OK for you, something of yours is listening on it, like some website’s development server: try another number.

Finally, stop the server in the other terminal with Ctrl + C, and check again:

4. The server is down

Ventana de terminal
./is-listening.sh 8080 || echo "Tell someone"

What you will see:

FAIL 127.0.0.1:8080 is not answering
Tell someone

|| runs the echo because the script failed. On a real server, that’s where a command that alerts you on your phone would go.

The second script saves a folder in backups/, in a compressed file with today’s date: web-2026-10-12.tar.gz. With the year first, sorting them by name is sorting them by date.

backup.sh
#!/usr/bin/env bash
# Saves a backup of a folder in backups/, in a file named with today's date.
# Usage: ./backup.sh FOLDER
set -euo pipefail
if [ "$#" -ne 1 ]; then
echo "Usage: $0 FOLDER" >&2
exit 2
fi
folder="$1"
if [ ! -d "$folder" ]; then
echo "The folder $folder does not exist" >&2
exit 1
fi
today="$(date +%Y-%m-%d)"
backup="backups/$(basename "$folder")-$today.tar.gz"
if [ -e "$backup" ]; then
echo "There is already a backup from today: $backup" >&2
exit 1
fi
mkdir -p backups
tar -czf "$backup" "$folder"
echo "Backup saved in $backup"

Two new commands:

  • basename keeps the last name in a path: from ~/projects/web it gets web.
  • tar bundles a folder into a single file, like a .zip. -c creates it, -z compresses it and -f says what it’s called. It works the same on Mac and Linux.

Before doing anything, it checks that you give it a folder, that it exists and that there isn’t already a backup from today. If something fails, it says so and finishes with an error, without touching anything.

5. A test folder and its backup

Ventana de terminal
chmod +x backup.sh
mkdir -p web
echo "Hello" > web/index.html
./backup.sh web
ls backups

What you will see:

Backup saved in backups/web-2026-10-12.tar.gz
web-2026-10-12.tar.gz

web plays the part of a website’s folder, with a single file. The script creates backups/ and saves the backup there. Your date will be today’s.

6. Try to break it

Ventana de terminal
./backup.sh web
echo $?
./backup.sh webb
echo $?

What you will see:

There is already a backup from today: backups/web-2026-10-12.tar.gz
1
The folder webb does not exist
1

There’s already a backup today, so it doesn’t overwrite it. And with a misspelled name, webb, it warns you and finishes with 1 instead of creating an empty backup.

7. Look at what's inside the backup

Ventana de terminal
tar -tzf backups/web-2026-10-12.tar.gz

What you will see:

web/
web/index.html

-t shows what’s inside without extracting it. Change the date to your backup’s (Tab completes it). A backup you haven’t checked isn’t a real backup.

The instructions for installing many programs are scripts. Homebrew’s, on the Mac, is /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)": it downloads a script with curl and hands it to bash. Now you can read that line, and open the script before running it.

And if you code:

  • The scripts in package.json are shell commands, and npm test fails if its exit code isn’t 0.
  • In GitHub Actions, each run: step is a piece of bash script, with -e by default. The step turns red when its exit code isn’t 0.
  • Git hooks, like the pre-commit that Husky sets up, are scripts: if one finishes with a code other than 0, Git cancels the commit.
  • Spaces around the =. name = Ana makes bash look for a command called name: name: command not found. Write name="Ana".
  • Brackets without spaces. ["$name" = "Ana"] gives [Ana: command not found, because [ is a command. Write [ "$name" = "Ana" ].
  • Running it with sh. sh is-listening.sh skips the shebang. On Ubuntu, sh isn’t bash but a simpler shell, and it answers set: Illegal option -o pipefail. Use ./is-listening.sh or bash is-listening.sh.
  • Writing it in a Windows editor. Windows ends each line with an extra invisible character, and on WSL the script fails with /usr/bin/env: ‘bash\r’: No such file or directory. In VS Code, click CRLF, at the bottom right, choose LF and save.

To catch them without running anything, paste your script into ShellCheck: it points out each problem and explains it. The two scripts in “Try it” pass it with no warnings.

  • A script is a text file with commands. The shebang, #!/usr/bin/env bash, says bash reads it; chmod +x gives it permission to run, and ./ tells the shell where it is.
  • Arguments arrive in $1, $2…; $# says how many there are and "$@" gives all of them. Variables are created without spaces (x="value") and read in quotes ("$x").
  • if checks whether a command went well, [ checks conditions and for repeats with each item in a list.
  • Every program finishes with an exit code, 0 if it went well. Your script chooses its own with exit, and set -euo pipefail makes it stop at the first error instead of carrying on blindly.
  • If the script goes past about 100 lines or works with data more than with programs, switch to Node or Python.
You write deploy.sh, which starts with #!/usr/bin/env bash. When you run it with ./deploy.sh, the terminal answers permission denied. What’s wrong with it?

On your Mac, the terminal uses zsh. You run ./hello.sh, which starts with #!/usr/bin/env bash. Which shell reads it?

You run ./backup.sh "My photos", with the quotes. What is $1 inside the script?

Your script goes into the website’s folder with cd and, on the next line, deletes the temporary files. It doesn’t have set -e. One day the folder doesn’t exist. What happens?

To find out if the server goes down, you run ./check.sh || ./alert.sh. One day it goes down, check.sh prints FAIL, but the alert doesn’t fire. Why could that be?

Your bash script reads a JSON file with orders, calculates the sales tax of each one with decimals and already has 180 lines. What do you do?

  • Bash Reference Manual: the complete reference.
  • Bash Guide, by Greg Wooledge: learning bash properly from the start, with the typical mistakes explained.
  • ShellCheck: checks your scripts. It can also be installed in the terminal.
phase-1 · lesson 8/10