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/fiwith[[ ]] - Repeat actions with
forandwhile - Organise the code with functions
- Handle arguments
$1,$#,$@and exit codes$? - Debug with
bash -xandshellcheck
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 [[:
$ bash -c ./nos2.shbash-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.
$ ./nos.shbash-ok (code 0)$ sh nos.shnos.sh: 2: [[: not found (code 127)$ bash nos.shbash-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:
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.
5.3.9(1)-releaseabsent/usr/bin/dash5.2.26(1)-release5.2.26(1)-release/usr/bin/bashHere 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:
chmod +x hello.sh./hello.shHello, bob!#!/bin/bash: the shebang, the system reads this path and starts that interpreterchmod +x: gives the execute permission to everyone (owner, group, others), except what the umask removes;chmod u+xgives 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:
$ 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}"User : aliceValue : 42Command 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.
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):
Date : 2026-11-13Accounts : 30On 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.
echo "Enter your name:"read -r firstnameecho "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:
| Variable | Content |
|---|---|
$USER | Current user name |
$HOME | Home directory |
$PWD | Current directory |
$RANDOM | Random 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."fiFile 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.
| Operator | True 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.
| Operator | True 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".
| Operator | Meaning |
|---|---|
-eq | equal |
-ne | not equal |
-lt | strictly less than |
-le | less than or equal |
-gt | strictly greater than |
-ge | greater than or equal |
score=85
if [[ $score -ge 90 ]]; then echo "Excellent"elif [[ $score -ge 70 ]]; then echo "Good"else echo "Needs work"fiGoodLoops
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.
for service in nginx ssh cron; do echo "Service: $service"doneService: nginxService: sshService: cronThe same loop also walks the files of a directory, using a pattern:
for file in /etc/*.conf; do echo "Config: $file"doneIt also counts over a numeric range:
for i in {1..5}; do echo "Iteration $i"donewhile, 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.
counter=1
while [[ $counter -le 3 ]]; do counter=$((counter + 1)) echo "Turn $counter"doneTurn 2Turn 3Turn 4Read 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.
while IFS= read -r line; do echo "→ $line"done < /etc/hostnameIFS=: keeps the leading and trailing spaces and tabs, whichreadremoves 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"=== 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 $():
full_name() { local first="$1" local last="$2" echo "${first} ${last}"}
result=$(full_name "alice" "martin")echo "Hello, $result!"Hello, alice martin!Script arguments
When you pass arguments to your script, they are available through special variables, set by Bash at launch:
| Variable | Content |
|---|---|
$0 | Script 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 1fi
echo "Script : $0"echo "Source : $1"echo "Dest : $2"echo "Nb args : $#"./copy.sh /etc/hosts /tmp/hosts.bakScript : ./copy.shSource : /etc/hostsDest : /tmp/hosts.bakNb args : 2Exit codes
Every command ends with an exit code: 0 = success, non-zero value = error. $? holds the code of the last command run.
ls /etc/passwdecho "Code: $?" # 0: success
ls /no-such-file 2>/dev/nullecho "Code: $?" # 2: errorIn a script, exit sets the code returned to the caller, whether it is a shell, cron or a CI pipeline:
if [[ ! -d "$1" ]]; then echo "Error: '$1' is not a directory." >&2 exit 1fi
# … processing …exit 0A 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):
| Case | Exit code |
|---|---|
A function whose last action is the false test, called under set -e, then an echo | 1, the echo is never displayed |
A false test in the middle of the script, followed by an echo | 0, the echo is displayed |
| A false test on the last line of the script | 1 |
| A function that ends with the false test, called on the last line | 1 |
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 1fi
directory="$1"
if [[ ! -d "$directory" ]]; then echo "Error: '$directory' is not a directory." >&2 exit 1fi
print_header "Report: $directory"echo "Date : $(date '+%Y-%m-%d %H:%M')"echo "User : $(id -un)"echo ""
nb_files=0for entry in "$directory"/*; do if [[ -f "$entry" ]]; then nb_files=$((nb_files + 1)) fidone
echo "Files : $nb_files"exit 0./generate-report.sh /etcThe 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:
=== Report: /tmp/demo ===Date : 2026-11-13 19:17User : ansible
Files : 2With /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:
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:
=== Report: /tmp/demo ===Date : 2026-11-13 19:17./generate-report.sh: line 27: USER: unbound variableThe 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:
Debian 13 (cron 3.0pl1-197)HOME=/home/ansibleLOGNAME=ansiblePATH=/usr/bin:/binSHELL=/bin/sh
AlmaLinux 10.2 (cronie)SHELL=/bin/shLOGNAME=ansibleHOME=/home/ansibleUSER=ansiblePATH=/usr/bin:/bin:/usr/sbin:/sbinA 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.
bash -x ./generate-report.sh /tmp/demoMeasured 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 +):
+ 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 0Look 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.
set -x # start of debugmv "$src" "$dst"set +x # end of debugshellcheck, 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:
No match for argument: shellcheckError: Unable to find a match: shellcheckYou 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:
ShellCheck - shell script analysis toolversion: 0.10.0license: GNU General Public License, version 3On RHEL, first enable the CRB repository, then install the EPEL RPM from the EPEL project website, following its instructions for your version.
# Debian/Ubuntusudo apt install shellcheck
# AlmaLinux and Rocky: the package comes from EPELsudo dnf install epel-releasesudo dnf install ShellCheckshellcheck my-script.shOn 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:
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.
| Symptom | Likely cause | Fix |
|---|---|---|
bash: line 1: ./np.sh: Permission denied (code 126) | Missing +x permission | chmod +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\r | Check #!/bin/bash; convert with dos2unix my-script.sh |
unb.sh: line 3: undefinedVar: unbound variable (code 1) | Undefined variable used with set -u | Initialise the variable or use ${VAR:-} |
dbl.sh: 2: [[: not found | Script 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/quote | Run shellcheck script.sh to locate it |
Key points
- A script starts with a shebang (
#!/bin/bashor#!/usr/bin/env bash) and is made executable withchmod +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 1or more = error; test the important commands or useset -eso that a failure is not masked.bash -xto debug,shellcheckto 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
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
Review
(0/0)Result saved on this device. It will be sent to your account at the next sync. Sync now
Score by domain
A domain groups several guides and gets several questions, so its score is more reliable than a per-topic score, which often rests on a single question.
Summary
Strengths
No topic passed at 80% on at least two questions yet.
Weak areas
No topic below the pass mark.
Recommended next
Hints before you try again?
Continue the course: Bash variables and parameters
A new full quiz with random questions
Work again only on the questions you missed