Skip to content
Français
Sync not enabled: your progress stays in this browser My learning
Select theme
Français

Write a Bash shell script: the complete guide

By updated

Improve this page

This guide gathers everything you need to write a Bash shell script, from the shebang to functions. Variables, conditions, loops, arguments, exit codes, debugging: each concept is explained with an example, then covered in depth in a dedicated page, linked where the topic appears. It is the reference guide of the scripting section, to read end to end when learning, or to consult section by section.

What you will learn

  • Create and run a script with a shebang and chmod +x
  • Use variables to store and reuse values
  • Write conditions if/then/fi with [[ ]]
  • Repeat actions with for and while
  • Organise the code with functions
  • Handle arguments $1, $#, $@ and exit codes $?
  • Debug with bash -x and shellcheck

When is it useful?

A Bash script pays off as soon as you repeat the same sequence of commands more than once or twice:

  • check disk space on ten servers and send an alert when a threshold is exceeded
  • create a user with their home directory, SSH keys and permissions in one command
  • build a daily report from nginx logs and send it by email
  • validate the state of a service before starting a deployment
  • convert or rename a batch of files following a pattern

Create and run your first script

The first line of a script, the shebang, tells which interpreter will run it. Without it, the shell that launches the script decides: Bash runs it with Bash, but dash (the sh of Debian and Ubuntu) runs it with itself, and anything specific to Bash breaks. Three small tests show it.

First test, without a shebang. The executable file nos2.sh contains a single line of Bash-specific syntax: [[ 1 == 1 ]] && echo bash-ok. When a shell launches an executable file that has no shebang, it interprets the file itself. Launched from Bash, it works. Launched from sh, which is dash on Debian, it fails with code 127, because dash does not know [[:

Output of bash -c ./nos2.sh and sh -c ./nos2.sh (Debian 13, 2026-11-13)
$ bash -c ./nos2.sh
bash-ok (code 0)
$ sh -c ./nos2.sh
./nos2.sh: 1: [[: not found (code 127)

Second test, with a shebang. The file nos.sh starts with #!/bin/bash, then contains the same line [[ 1 == 1 ]] && echo bash-ok, and it is executable. Launched as a program (./nos.sh), the system reads the first line and picks Bash, whatever the caller's shell. Launched through bash, it works too. Launched with sh nos.sh, the shebang is ignored: dash reads the file, and it fails with code 127.

Output of ./nos.sh, sh nos.sh and bash nos.sh (Debian 13, /bin/sh to dash, 2026-11-13)
$ ./nos.sh
bash-ok (code 0)
$ sh nos.sh
nos.sh: 2: [[: not found (code 127)
$ bash nos.sh
bash-ok (code 0)

Third test, which does not depend on the shebang: finding out which shell hides behind sh. The file version.sh contains a single line:

Terminal window
echo "${BASH_VERSION:-absent}"

In this test, bash version.sh and sh version.sh name the interpreter themselves: a shebang would be ignored in both cases. On Ubuntu 26.04, with Bash 5.3.9 and where /bin/sh points to dash, the file launched by bash sees the variable, and launched by sh it does not. On AlmaLinux 10.2, /bin/sh is Bash itself (5.2.26): both launches give the same answer, and the difference disappears.

Output of bash version.sh, then sh version.sh, then readlink -f /bin/sh (Ubuntu 26.04, 2026-11-13)
5.3.9(1)-release
absent
/usr/bin/dash
Same commands on AlmaLinux 10.2
5.2.26(1)-release
5.2.26(1)-release
/usr/bin/bash

Here is the example script of this page:

#!/bin/bash
echo "Hello, $USER!"

Save this file as hello.sh, then make it executable and run it from the current directory, where the shell does not look for commands by default:

Terminal window
chmod +x hello.sh
./hello.sh
Output
Hello, bob!
  • #!/bin/bash: the shebang, the system reads this path and starts that interpreter
  • chmod +x: gives the execute permission to everyone (owner, group, others), except what the umask removes; chmod u+x gives it to the owner only
  • ./: runs the script from the current directory

The difference between chmod +x and chmod u+x shows in the permissions displayed by stat -c %A. With a umask of 0022, a new file is -rw-r--r--. After chmod +x, all three categories get the execute permission. After chmod u+x, only the owner gets it:

Permissions before and after chmod (Debian 13, umask 0022, 2026-11-13)
$ touch f1 ; stat -c %A f1
-rw-r--r--
$ chmod +x f1 ; stat -c %A f1
-rwxr-xr-x
$ touch f2 ; chmod u+x f2 ; stat -c %A f2
-rwxr--r--

Variables

A variable stores a value to reuse it later. In Bash, the rule that traps every beginner is about spacing: the declaration takes no space around the = (name="alice", never name = "alice"), because with spaces Bash thinks it must run a command called name. When reading it, you prefix the name with $ or wrap it in ${}, the latter being mandatory as soon as text follows the name directly. The page Bash variables and parameters goes further.

#!/bin/bash
name="alice"
number=42
echo "User : $name"
echo "Value : ${number}"
Output
User : alice
Value : 42

Command substitution

Command substitution captures the standard output of a command and stores it in a variable. The modern $(...) form replaces the old backtick notation: it nests cleanly and reads without ambiguity. It is the mechanism that lets a script react to the real state of the system, such as today's date or the number of accounts.

Terminal window
today=$(date '+%Y-%m-%d')
nb_users=$(wc -l < /etc/passwd)
echo "Date : $today"
echo "Accounts : $nb_users"

Both values depend on your machine. Measured on Ubuntu 26.04 on 13 November 2026 (UTC date of the command: 2026-11-13T19:17:48Z):

Output (Ubuntu 26.04, 13 November 2026)
Date : 2026-11-13
Accounts : 30

On AlmaLinux 10.2, the same day, the date is identical and the number of accounts is 23: /etc/passwd does not have the same content from one distribution to another. The date uses the YYYY-MM-DD format requested by date '+%Y-%m-%d'.

Read user input

The read command pauses the script and waits for keyboard input, which it stores in the given variable. It is handy for an interactive script, but an automated script (cron, CI) has nobody to answer: keep read for tools run by hand.

Terminal window
echo "Enter your name:"
read -r firstname
echo "Hello, $firstname!"

The -r option turns off the interpretation of backslashes in the input: a pasted Windows path or a line containing \n comes out intact. Always use read -r: shellcheck flags the other form.

Useful automatic variables

A few variables exist without any declaration: $RANDOM and $PWD come from Bash, $USER and $HOME from the environment the system hands to the shell ($USER is not always defined, see below). These four come up in almost every administration script, to name a file, build a path or pick a random value:

VariableContent
$USERCurrent user name
$HOMEHome directory
$PWDCurrent directory
$RANDOMRandom number between 0 and 32767

Conditions

The if/then/fi structure runs a block when a condition is true. Use [[ ]] (double brackets), safer and more readable than [ ]. The page Bash conditions details the three forms of test and case.

#!/bin/bash
file="$1"
if [[ -f "$file" ]]; then
echo "The file exists."
else
echo "The file cannot be found."
fi

File tests

In system administration, half of the conditions are about files: does the script exist, is the directory there, do I have the right to write here. These one-letter operators return true or false and are used as is inside [[ ]]. The most common is -f, which checks that a regular file exists before reading it.

OperatorTrue when…
-f "$f"$f is a regular file
-d "$f"$f is a directory
-e "$f"$f exists (file or directory)
-r "$f"$f is readable
-w "$f"$f is writable
-x "$f"$f is executable

String tests

String tests mostly validate an argument: is it empty, is it exactly this value. The classic trap is -z versus -n: -z is true when the string is empty, -n when it contains something. Inside [[ ]], an empty unquoted variable remains an empty operand and the test works; inside the older [ ] command, it vanishes and triggers unary operator expected. Keep the quotes out of habit: they protect you in both cases.

OperatorTrue when…
-z "$s"$s is empty
-n "$s"$s is not empty
"$a" == "$b"the two strings are equal
"$a" != "$b"the two strings differ

Numeric tests

Bash clearly separates comparing numbers from comparing strings. For numbers, use these two-letter operators (-eq, -lt...), not the < or > signs, which compare alphabetically. Writing [[ "$a" -gt "$b" ]] compares 9 and 10 as integers, whereas > would place "10" before "9".

OperatorMeaning
-eqequal
-nenot equal
-ltstrictly less than
-leless than or equal
-gtstrictly greater than
-gegreater than or equal
Terminal window
score=85
if [[ $score -ge 90 ]]; then
echo "Excellent"
elif [[ $score -ge 70 ]]; then
echo "Good"
else
echo "Needs work"
fi
Output
Good

Loops

for, iterate over a list

The for loop repeats a block for each item of a list. That list can be written by hand, produced by a file pattern (/etc/*.conf) or a range {1..5}. It is the form to prefer when you know in advance the set of items to process. The page Bash loops also covers until.

Terminal window
for service in nginx ssh cron; do
echo "Service: $service"
done
Output
Service: nginx
Service: ssh
Service: cron

The same loop also walks the files of a directory, using a pattern:

Terminal window
for file in /etc/*.conf; do
echo "Config: $file"
done

It also counts over a numeric range:

Terminal window
for i in {1..5}; do
echo "Iteration $i"
done

while, conditional loop

Where for walks a known set, while repeats as long as a condition stays true, without knowing in advance how many turns there will be. It is the loop to pick to wait for a service to start, or to consume an input until it runs out. Make sure the condition eventually becomes false, otherwise the loop runs forever.

Terminal window
counter=1
while [[ $counter -le 3 ]]; do
counter=$((counter + 1))
echo "Turn $counter"
done
Output
Turn 2
Turn 3
Turn 4

Read a file line by line

Reading a file line by line is a daily need: walk a list of servers, process a log, apply an action per entry. The while IFS= read -r line combination is the correct pattern to do it without surprises. Without IFS=, Bash strips the leading and trailing spaces; without -r, it interprets backslashes. Together, they guarantee that each line arrives intact.

Terminal window
while IFS= read -r line; do
echo "→ $line"
done < /etc/hostname
  • IFS=: keeps the leading and trailing spaces and tabs, which read removes otherwise
  • -r: preserves backslashes

Functions

A function groups reusable instructions under a name, to avoid repeating the same block in several places. In Bash, one constraint is worth knowing straight away: a function must be declared before the line that calls it, because the script is read from top to bottom. So place your functions at the top of the file, right after the shebang. The page Bash functions details declaration, arguments and return values.

#!/bin/bash
print_header() {
local title="$1"
echo ""
echo "=== $title ==="
}
print_header "System report"
print_header "End"
Output
=== System report ===
=== End ===
  • local: the variable stays local to the function, essential to avoid side effects
  • $1, $2…: arguments passed to the function (independent from the script's arguments)

Return a text value

A function returns an exit code (0–255), not a string. To return text, print it with echo and capture it with $():

Terminal window
full_name() {
local first="$1"
local last="$2"
echo "${first} ${last}"
}
result=$(full_name "alice" "martin")
echo "Hello, $result!"
Output
Hello, alice martin!

Script arguments

When you pass arguments to your script, they are available through special variables, set by Bash at launch:

VariableContent
$0Script name
$1, $2…First, second argument
$#Total number of arguments
$@All the arguments (list)
#!/bin/bash
if [[ $# -ne 2 ]]; then
echo "Usage: $0 <source> <destination>" >&2
exit 1
fi
echo "Script : $0"
echo "Source : $1"
echo "Dest : $2"
echo "Nb args : $#"
Terminal window
./copy.sh /etc/hosts /tmp/hosts.bak
Output
Script : ./copy.sh
Source : /etc/hosts
Dest : /tmp/hosts.bak
Nb args : 2

Exit codes

Every command ends with an exit code: 0 = success, non-zero value = error. $? holds the code of the last command run.

Terminal window
ls /etc/passwd
echo "Code: $?" # 0: success
ls /no-such-file 2>/dev/null
echo "Code: $?" # 2: error

In a script, exit sets the code returned to the caller, whether it is a shell, cron or a CI pipeline:

Terminal window
if [[ ! -d "$1" ]]; then
echo "Error: '$1' is not a directory." >&2
exit 1
fi
# … processing …
exit 0

A false test as the last statement returns 1

The code 1 of a false test mostly surprises you in the short form [[ -f "$file" ]] && command. When the test is false, command does not run, and the whole expression is worth 1. In the middle of a script, that 1 goes unnoticed, even under set -e: a failure inside an && list, except for its last command, does not stop the script. The trap shows up when that line is the last statement of the script or of a function: its 1 then becomes the exit code, and a caller running under set -e stops.

Four small scripts measured it on 13 November 2026, with the same result on Ubuntu 26.04 (Bash 5.3.9) and on AlmaLinux 10.2 (Bash 5.2.26):

CaseExit code
A function whose last action is the false test, called under set -e, then an echo1, the echo is never displayed
A false test in the middle of the script, followed by an echo0, the echo is displayed
A false test on the last line of the script1
A function that ends with the false test, called on the last line1

The same mechanism lurks in the complete example below. Replace its if with the form [[ -f "$entry" ]] && nb_files=$((nb_files + 1)), on a directory whose last sorted entry is a subdirectory: the loop then ends on a false test. The script is nevertheless not stopped, because an echo follows the loop and, under set -e, the failure of a test in an && list stops nothing as long as it is not the last command of the script. It displayed Files : 1 and returned 0. The form with if avoids the trap in every case, and it is the one used in the example.


Complete example

Here is a realistic script that brings together everything above: a display function, the validation of the number of arguments, a directory test, a for counting loop and explicit exit codes. Read it as a template to reuse. The set -euo pipefail line at the top stops the script when a command fails (except inside a test such as if), on an undefined variable, or on a failure inside a pipe; the page Robust Bash scripts explains it in detail. Validating the arguments at the start is a good reflex for any administration script.

#!/bin/bash
# generate-report.sh: report on a directory
# Usage: ./generate-report.sh <directory>
set -euo pipefail
print_header() {
local title="$1"
echo ""
echo "=== $title ==="
}
if [[ $# -ne 1 ]]; then
echo "Usage: $0 <directory>" >&2
exit 1
fi
directory="$1"
if [[ ! -d "$directory" ]]; then
echo "Error: '$directory' is not a directory." >&2
exit 1
fi
print_header "Report: $directory"
echo "Date : $(date '+%Y-%m-%d %H:%M')"
echo "User : $(id -un)"
echo ""
nb_files=0
for entry in "$directory"/*; do
if [[ -f "$entry" ]]; then
nb_files=$((nb_files + 1))
fi
done
echo "Files : $nb_files"
exit 0
Terminal window
./generate-report.sh /etc

The output has this shape: a header, the date and time, the user name, then the number of regular files in the directory. Measured on Ubuntu 26.04 on 13 November 2026, first with a test directory created for the occasion (mkdir /tmp/demo && touch /tmp/demo/a /tmp/demo/b), which gives a reproducible output:

Output of ./generate-report.sh /tmp/demo (Ubuntu 26.04), exit code 0
=== Report: /tmp/demo ===
Date : 2026-11-13 19:17
User : ansible
Files : 2

With /etc, only the number changes: 76 files on this Ubuntu, 78 on AlmaLinux 10.2, always with code 0. The script therefore runs to the end under set -e, loop included. The two planned error cases return code 1 and write their message on the error output:

Outputs with no argument, then with a nonexistent path, exit code 1
Usage: ./generate-report.sh <directory>
Error: '/nonexistent' is not a directory.

The template writes $(id -un) rather than $USER, because of a trap of set -u: an undefined variable stops the script, and USER is not always defined. env -u USER removes the USER variable alone from the environment. If the user line were written with $USER, the script would stop at that line with code 1, after already printing the header and the date:

Output of env -u USER ./generate-report.sh /tmp/demo with $USER in the script, exit code 1
=== Report: /tmp/demo ===
Date : 2026-11-13 19:17
./generate-report.sh: line 27: USER: unbound variable

The id -un command queries the system instead of reading the environment: it answers even when USER is missing.

This case is not theoretical: under cron, the variables depend on the distribution. A task * * * * * env > /tmp/env-cron.txt gives on Debian 13 (cron package 3.0pl1-197) a list without USER, with only LOGNAME. On AlmaLinux 10.2 (cronie), USER is present:

Variables seen by a cron task (user ansible, 2026-11-13)
Debian 13 (cron 3.0pl1-197)
HOME=/home/ansible
LOGNAME=ansible
PATH=/usr/bin:/bin
SHELL=/bin/sh
AlmaLinux 10.2 (cronie)
SHELL=/bin/sh
LOGNAME=ansible
HOME=/home/ansible
USER=ansible
PATH=/usr/bin:/bin:/usr/sbin:/sbin

A script launched by cron on Debian that writes $USER therefore stops under set -u. Use $(id -un) or $LOGNAME. The cron PATH also contains fewer directories than the one of a terminal, and it has no /usr/sbin on Debian: write the full path of administration commands.


Debug a script

bash -x, see each command before it runs

Run through bash -x, the script prints each executed line before it runs, prefixed with +, with the variables already substituted. It is a simple way to follow the execution step by step and spot the value that goes wrong. The page Debug a Bash script goes deeper into these tools.

Terminal window
bash -x ./generate-report.sh /tmp/demo

Measured on Ubuntu 26.04 on 13 November 2026 (excerpt: a ... line replaces the rest of the header, the date and the user name; standard output and trace lines are mixed, and trace lines start with +):

Output (excerpt, Ubuntu 26.04)
+ set -euo pipefail
+ [[ 1 -ne 1 ]]
+ directory=/tmp/demo
+ [[ ! -d /tmp/demo ]]
+ print_header 'Report: /tmp/demo'
...
+ nb_files=0
+ for entry in "$directory"/*
+ [[ -f /tmp/demo/a ]]
+ nb_files=1
+ for entry in "$directory"/*
+ [[ -f /tmp/demo/b ]]
+ nb_files=2
+ echo 'Files : 2'
Files : 2
+ exit 0

Look at the values already substituted: [[ -f /tmp/demo/a ]] shows the real path being tested, nb_files=1 then nb_files=2 show the counter moving forward, and [[ 1 -ne 1 ]] is the test on the number of arguments (one argument received, one expected). An unexpected value in these places points straight at the faulty line. The ++ prefix marks a command run inside a substitution, like the date of the script.

set -x / set +x inside the script

Running the whole script with bash -x soon becomes unreadable on a long script. The set -x and set +x directives surround the only portion you care about: tracing starts at the first, stops at the second. It is the method to prefer to isolate a suspicious command without drowning the output.

Terminal window
set -x # start of debug
mv "$src" "$dst"
set +x # end of debug

shellcheck, static analysis

shellcheck is a static analyser: it reads the script without running it and reports syntax errors and classic traps, starting with unquoted variables. Run it on a script before launching it for the first time; it is also a common tool of CI pipelines. Each warning carries a code (SC2086, etc.) that links to a detailed explanation online.

On Debian and Ubuntu, shellcheck is in the distribution repositories: Ubuntu 26.04 ships version 0.11.0 (package 0.11.0-2), installed with apt install on 13 November 2026. On RHEL and its derivatives, it is not: it comes from EPEL, under the package name ShellCheck. On AlmaLinux 10.2, dnf install shellcheck fails without EPEL:

Output of sudo dnf install -y shellcheck (AlmaLinux 10.2)
No match for argument: shellcheck
Error: Unable to find a match: shellcheck

You therefore have to enable EPEL before installing the ShellCheck package. On AlmaLinux and Rocky, dnf install epel-release is enough. On AlmaLinux 10.2, it installs epel-release 10-6.el10 (extras repository), then dnf install ShellCheck installs version 0.10.0 from the epel repository:

Output of shellcheck --version (AlmaLinux 10.2, ShellCheck 0.10.0-3.el10_0, 2026-11-13)
ShellCheck - shell script analysis tool
version: 0.10.0
license: GNU General Public License, version 3

On RHEL, first enable the CRB repository, then install the EPEL RPM from the EPEL project website, following its instructions for your version.

Terminal window
# Debian/Ubuntu
sudo apt install shellcheck
# AlmaLinux and Rocky: the package comes from EPEL
sudo dnf install epel-release
sudo dnf install ShellCheck
Terminal window
shellcheck my-script.sh

On a script whose line 3 writes rm $f, shellcheck answers as follows. The -f gcc option gives the same finding on a single line, handy in an editor or a CI job:

Output of shellcheck my-script.sh
In my-script.sh line 3:
rm $f
^-- SC2086 (info): Double quote to prevent globbing and word splitting.
Did you mean:
rm "$f"

Troubleshooting

Beginner scripting errors repeat from one script to the next, and most of them can be read straight from the error message. The messages below were measured on 13 November 2026 on Ubuntu 26.04 (Bash 5.3.9, sh is dash) and on AlmaLinux 10.2 (Bash 5.2.26, sh is Bash): they sometimes differ from one version to another, and the table says so. Two reflexes cover almost every case: check the execute permission and the shebang for launch problems, run shellcheck for syntax errors.

SymptomLikely causeFix
bash: line 1: ./np.sh: Permission denied (code 126)Missing +x permissionchmod +x my-script.sh
/bin/bash^M: bad interpreter: No such file or directory (Ubuntu 26.04, code 126) or cannot execute: required file not found (AlmaLinux 10.2, code 127)Wrong shebang or Windows line endings (CRLF): the system looks for bash\rCheck #!/bin/bash; convert with dos2unix my-script.sh
unb.sh: line 3: undefinedVar: unbound variable (code 1)Undefined variable used with set -uInitialise the variable or use ${VAR:-}
dbl.sh: 2: [[: not foundScript launched with sh script.sh on Debian or Ubuntu: sh is dash here, which is the interpreter and ignores the shebang (on AlmaLinux, sh is Bash and the script runs)Run with ./script.sh or bash script.sh
syntax error near unexpected token `fi' or syntax error: unexpected end of file (code 2)Missing fi/done/quoteRun shellcheck script.sh to locate it

Key points

  • A script starts with a shebang (#!/bin/bash or #!/usr/bin/env bash) and is made executable with chmod +x.
  • Variables are declared without spaces around the = and used in quotes: "$var".
  • Use [[ ]] for tests, safer than [ ].
  • Functions declare their internal variables with local.
  • $1, $2, $#, $@ give access to the arguments passed to the script.
  • exit 0 = success, exit 1 or more = error; test the important commands or use set -e so that a failure is not masked.
  • bash -x to debug, shellcheck to catch errors beforehand.

Knowledge check

Check that the essentials of this guide stuck. The questions cover only what has just been explained here.

Knowledge check

Check what you have learned with this interactive quiz

6 questions
6 min
70% to pass

How it works

  • The timer starts when you click Start
  • Multiple choice, true/false and short answer questions
  • You can move between questions
  • Detailed results are shown at the end

Starts the quiz and the timer