Every morning you type the same commands, in the same order, to start your project. If you write those commands in a file once, tomorrow you only need to run the file. This file is called a shell script: a text file of terminal commands that run in order, from top to bottom. A script is like a recipe. The steps are written once, and every time you cook you follow them, with ingredients that may change: 2 servings today, 4 tomorrow. The steps of the recipe are the commands in the script. The ingredients are the arguments: the text you type after the script's name when you run it.
Your first script: greet.sh
The script below greets the name you give it, three times:
#!/bin/bash
# greet.sh: greets the name given as the first argument
name=$1
if [ -z "$name" ]; then
echo "No name given. Usage: ./greet.sh NAME"
exit 1
fi
for i in 1 2 3; do
echo "Greeting $i for $name"
done
- Line 1,
#!/bin/bash, is called the shebang. It tells the system which program reads this file (its interpreter): bash, which is at/bin/bash. The shebang must be on the first line, and it must start exactly with#!. - Any other line that starts with
#is a comment: a note for humans, skipped when the script runs. - The rest are commands you would normally type in the terminal, run one by one from the top.
name=$1,ifandforare explained in the sections below.
Save it as greet.sh, give it execute permission, then run it:
$ chmod +x greet.sh
$ ./greet.sh Budi
Greeting 1 for Budi
Greeting 2 for Budi
Greeting 3 for Budi
chmod +x greet.shgives execute (x) permission, as in the Permission lesson. Without that permission,./greet.shis refused:bash: ./greet.sh: Permission denied../means "the file in this folder". Without./, bash looks forgreet.shin the folders listed in PATH. The file is not there, so bash answersbash: greet.sh: command not found.bash greet.sh Budiworks too, even withoutchmod. In this command the program you run is bash, and bash itself reads the file, so the file does not need execute permission. The shebang is only used when you run the file directly, with./greet.sh.
The shebang line has a few options. This lesson uses #!/bin/bash, because that path exists on Linux and macOS:
| Shebang | When to pick it |
|---|---|
#!/bin/bash |
The default in this lesson. But on macOS, /bin/bash is the old bash 3.2, so features from bash 4 and later don't work. For example echo {01..03}, which writes the numbers 01 to 03: bash 4 and later print 01 02 03, bash 3.2 prints 1 2 3. |
#!/usr/bin/env bash |
Your script needs a newer bash. env runs the first bash it finds in PATH, for example bash 5 from Homebrew on macOS. |
#!/bin/sh |
The script must run on systems that may not have bash. Use only basic features, because on Ubuntu /bin/sh is dash, a simple shell without the extra features of bash. In dash, {01..03} stays as written, and [[ (a form of check that bash has and dash does not) gets the answer [[: not found. |
Variables and arguments
name=$1stores the first argument in the variablename. No spaces around the=.$namereads the value of that variable. Inside double quotes, as in"Greeting $i for $name", variables are still replaced by their values.$1is the first argument,$2the second,$#the number of arguments, and$0the script's name.
Spaces separate arguments. If you want a two-word name to be one argument, put quotes around the name. Compare the results with and without quotes:
$ ./greet.sh "Budi Santoso"
Greeting 1 for Budi Santoso
Greeting 2 for Budi Santoso
Greeting 3 for Budi Santoso
$ ./greet.sh Budi Santoso
Greeting 1 for Budi
Greeting 2 for Budi
Greeting 3 for Budi
Without quotes, Budi becomes $1 and Santoso becomes $2. This script does not use $2, so Santoso does not appear.
Now change line 3 to name = $1, with spaces around the =. First guess what happens, then look at the result:
$ ./greet.sh Budi
./greet.sh: line 3: name: command not found
No name given. Usage: ./greet.sh NAME
Bash reads line 3 as a command called name, with two arguments: = and Budi. There is no command called name, so bash answers command not found. The variable name is never filled, so when the if below checks name, it is empty.
if: check before you go
[ -z "$name" ]is a test: a check whose result is true or false.-zis true when the text is empty (zero length). The spaces after[and before]are required.thenopens the part that runs when the test is true, andfi(if backwards) closes that part. The;beforethenmeans the same as a line break. The part that runs when the test is false starts withelse, and you add another test withelif.exit 1stops the script with failure code 1. The lines below it don't run any more.
Other tests you'll use often:
| Test | True when |
|---|---|
-z "$a" / -n "$a" |
the text is empty / not empty |
"$a" = "$b" / "$a" != "$b" |
two texts are equal / different |
$x -eq 3, -ne, -lt, -gt, -le, -ge |
numbers equal, not equal, less than, greater than, less or equal, greater or equal |
-f file.txt / -d folder |
that file / folder exists |
for: repeat for each item
for i in 1 2 3; do ... done takes the list after in, then runs the part between do and done once for each item. In each round, i holds the current item: 1, then 2, then 3. There are three items, so there are three rounds, and the echo inside shows three lines. If you add the item 4, you get four lines. The list can hold anything: for f in *.txt repeats for every .txt file.
$?: success or failure
Every command finishes with an exit code: a number that shows whether the command worked or failed. $? holds the exit code of the last command. In this example, greet.sh runs with no name:
$ ./greet.sh
No name given. Usage: ./greet.sh NAME
$ echo $?
1
| Exit code | Meaning |
|---|---|
0 |
success |
1 |
failure, like the exit 1 in our script |
126 |
the file exists but may not be run (forgot chmod +x) |
127 |
the command was not found |
A script that ends without exit takes the exit code of its last command. In greet.sh, that last command is echo, which succeeds, so the exit code is 0. Read $? right after the command you want to check, because the next command overwrites it.
⚠️ Script won't run? Check these four
- Spaces around
=.name = $1ends inname: command not found. Writename=$1. - A variable without quotes inside
[ ]. IfnameholdsBudi Santoso,[ -z $name ]becomes[ -z Budi Santoso ]. Bash refuses that test with the message[: Budi: binary operator expected: in the place ofBudi, it expected an operator such as=. Always write"$name". - Forgetting
chmod +xor./. Withoutchmod +x, you getPermission denied(exit code 126). Without./, you getcommand not found(127). - A script saved with Windows line endings (CRLF). Windows marks the end of a line with two hidden characters (CRLF), Linux with one (LF). The extra character from Windows becomes part of the shebang: the system looks for a program called
/bin/bashplus that character, then answersbad interpreter: No such file or directory. Save with LF line endings. In VS Code, click the CRLF label in the bottom right corner, then choose LF.
TL;DR: A shell script is a text file of terminal commands that run from top to bottom. The first line #!/bin/bash (called the shebang) tells the system which program reads and runs the file: bash. Give it execute permission with chmod +x greet.sh, then run it with ./greet.sh Budi (or bash greet.sh Budi). Here Budi is an argument: text typed after the script's name. $1 holds the first argument. Variables are written without spaces around = (name=$1) and read with "$name". if [ -z "$name" ]; then ... fi first checks whether name is empty, and exit 1 stops the script with a failure code. for i in 1 2 3; do ... done runs the commands between do and done once per item: with one echo inside, you get three lines. $? holds the last command's exit code (its result number): 0 is success, anything else is failure.
⚡ Your first script
Write:
#!/bin/bash
name=$1
if [ -z "$name" ]; then
echo "No name given. Usage: ./greet.sh NAME"
exit 1
fi
for i in 1 2 3; do
echo "Greeting $i for $name"
done
Guess first: what is the #!/bin/bash line at the very top for?
It tells the system which program reads this file (its interpreter): bash, found at /bin/bash. This line is called the shebang, and it must be on the first line.
Meaning: A shell script is a text file of terminal commands that run from top to bottom. This script greets one name three times. Save it as greet.sh.
⚡ Give it permission, then run it
Write:
chmod +x greet.sh
./greet.sh Budi
Meaning: chmod +x gives execute permission. Without it, ./greet.sh is refused with Permission denied. ./ means "the file in this folder". Budi is the first argument (text after the script's name), and the script reads it through $1.
⚡ Variables without spaces
Meaning: name=$1 stores the first argument in the variable name, and there can be no spaces around =. If you write name = $1, bash reads name as a command and answers command not found. Read the value with "$name", quotes included.
⚡ Check first, then repeat
Meaning: [ -z "$name" ] is true when name is empty, and exit 1 stops the script with a failure code. for i in 1 2 3 runs the commands in do ... done once per item, so the echo inside shows three lines.