Learn to Code
All tracks
Learn to Code

Free lessons from scratch to pro — every language, databases and DevOps.

AboutContactPrivacy PolicyTerms of Use

Your progress is saved in this browser. © 2026 Learn to Code

SH
Bash Scripting
0/12 completed
Beginner
Your first scriptVariables and argumentsQuoting and expansionInput, output and redirection
Intermediate
Conditions and testsLoopsFunctionsArrays and string tricks
Advanced
Text processing: grep, sed and awkError handling and debugging
Pro
Cron and schedulingProduction-ready scripts
Tracks / Bash Scripting / Intermediate

Conditions and tests

Scripts need to make decisions: does this file exist? did the build pass? is the disk nearly full? In Bash, every decision is based on a command's exit code: 0 counts as true, anything else as false.

if

bash
if grep -q "^you:" /etc/passwd; then
  echo "user 'you' exists"
fi

if ping -c1 -W1 no-such-host.invalid > /dev/null 2>&1; then
  echo "host is up"
else
  echo "host is unreachable"
fi
Output
user 'you' exists
host is unreachable

The shape is always if COMMAND; then … elif COMMAND; then … else … fi. Any command works as the condition, which is why if grep -q … and if mkdir dir are so common.

[[ ]]: testing values

To compare strings and numbers or check files, use the test command [[ … ]]. It succeeds or fails like any other command:

bash
name="asha"
age=31
if [[ $name == "asha" ]]; then echo "hello asha"; fi
if [[ $age -ge 18 ]]; then echo "adult"; fi
if [[ -z $missing ]]; then echo "missing is empty"; fi
[[ 5 -lt 3 ]]
echo "5 -lt 3 → exit code $?"
Output
hello asha
adult
missing is empty
5 -lt 3 → exit code 1

The spaces inside [[ and ]] are required: [[$age -ge 18]] is an error.

String tests

Test True when
[[ $a == $b ]] Equal (the right side can be a glob: [[ $f == *.log ]])
[[ $a != $b ]] Not equal
[[ $a =~ regex ]] Matches a regular expression
[[ -z $a ]] Empty
[[ -n $a ]] Not empty

Number tests

Test Meaning
-eq -ne equal, not equal
-lt -le less than, less or equal
-gt -ge greater than, greater or equal

Or use arithmetic (( )), which reads like other languages:

bash
disk=91
if (( disk > 90 )); then
  echo "CRITICAL: disk at ${disk}%"
elif (( disk > 75 )); then
  echo "warning: disk at ${disk}%"
else
  echo "ok"
fi
Output
CRITICAL: disk at 91%

⚠️ Inside [[ ]], < and > compare text, alphabetically: [[ 10 < 9 ]] is true, because "1" sorts before "9". Use -lt or (( )) for numbers.

File tests

Test True when the path…
-e path exists
-f path is a regular file
-d path is a directory
-s path is a file and not empty
-r -w -x path is readable, writable, executable by you
-L path is a symbolic link
a -nt b a is newer than b
bash
config=/etc/hostname
if [[ -f $config ]]; then
  echo "$config exists ($(wc -c < "$config") bytes)"
fi
[[ -d /var/log ]] && echo "/var/log is a directory"
[[ -w /etc/passwd ]] || echo "you can't write /etc/passwd (good!)"
mkdir -p ~/backups
[[ -x ~/backups ]] && echo "you can enter ~/backups"
Output
/etc/hostname exists (7 bytes)
/var/log is a directory
you can't write /etc/passwd (good!)
you can enter ~/backups

Combining conditions

bash
user="admin"
port=8080
if [[ $user == "admin" && $port -gt 1024 ]]; then echo "both true"; fi
if [[ $user == "root" || $port -eq 8080 ]]; then echo "at least one true"; fi
if [[ ! -e /tmp/lock ]]; then echo "no lock file"; fi
if grep -q you /etc/passwd && [[ -d /home/you ]]; then echo "user and home exist"; fi
Output
both true
at least one true
no lock file
user and home exist

Inside [[ ]] use &&, || and !. Between commands, && and || chain them as you saw in the first lesson.

Pattern and regex matching

bash
for file in report.pdf photo.JPG notes.txt; do
  if [[ $file == *.pdf ]]; then
    echo "$file: PDF"
  elif [[ ${file,,} == *.jpg ]]; then
    echo "$file: image"
  else
    echo "$file: other"
  fi
done

email="asha@example.com"
if [[ $email =~ ^[^@]+@([^@]+)$ ]]; then
  echo "valid, domain is ${BASH_REMATCH[1]}"
fi
version="v2.14.3"
if [[ $version =~ ^v([0-9]+)\.([0-9]+)\.([0-9]+)$ ]]; then
  echo "major ${BASH_REMATCH[1]}, minor ${BASH_REMATCH[2]}, patch ${BASH_REMATCH[3]}"
fi
Output
report.pdf: PDF
photo.JPG: image
notes.txt: other
valid, domain is example.com
major 2, minor 14, patch 3

=~ stores the regex groups in the array BASH_REMATCH. Don't put quotes around the regex: quoted, it's matched as plain text.

[[ ]] vs [ ] vs test

You'll see three spellings:

  • [ … ] and test … are the old POSIX commands. They work in every shell (sh too), but unquoted variables inside them break on spaces and empty values.
  • [[ … ]] is Bash's improved version: no word splitting inside, &&/||, patterns and =~.
bash
empty=""
[ $empty = "x" ] && echo yes
echo "single brackets: exit $?"
[[ $empty = "x" ]] && echo yes
echo "double brackets: exit $?"
Output
bash: [: =: unary operator expected
single brackets: exit 2
double brackets: exit 1

The [ ] version became [ = "x" ], which isn't a valid test. Use [[ ]] in Bash scripts and [ "$var" = x ] (quoted!) in sh scripts.

case: many choices

When one value can be one of several things, case is cleaner than a chain of elifs. It's the standard way to handle sub-commands like start/stop:

service.sh
#!/usr/bin/env bash
case "$1" in
  start)
    echo "starting the app" ;;
  stop|halt)
    echo "stopping the app" ;;
  restart)
    echo "stopping the app"
    echo "starting the app" ;;
  *.conf)
    echo "loading config file $1" ;;
  "")
    echo "usage: $0 {start|stop|restart|FILE.conf}" >&2
    exit 1 ;;
  *)
    echo "unknown command: $1" >&2
    exit 1 ;;
esac
bash
bash service.sh start
bash service.sh halt
bash service.sh prod.conf
bash service.sh dance
bash service.sh
Output
starting the app
stopping the app
loading config file prod.conf
unknown command: dance
usage: service.sh {start|stop|restart|FILE.conf}

Each choice is a glob pattern (| means "or"), ends with ), and its commands end with ;;. *) catches everything else. The block closes with esac (case backwards, like fi).

Asking for confirmation

A safety check every destructive script should have:

cleanup.sh
#!/usr/bin/env bash
read -rp "Delete all logs in /tmp/app? [y/N] " answer
if [[ ${answer,,} == y || ${answer,,} == yes ]]; then
  echo "deleting…"
else
  echo "cancelled"
fi
bash
bash cleanup.sh
Output
Delete all logs in /tmp/app? [y/N] n
cancelled

The capital N in [y/N] is a convention: it's what happens if you just press Enter.

Practice

  1. Write age.sh that takes an age as $1 and prints child (under 13), teen (13–19) or adult. Print a usage message if no age is given.
  2. Write check-file.sh PATH that says whether the path is a file, a directory, or doesn't exist, and whether you can write to it.
  3. Use case to print the type of a file from its extension: images (jpg|png|gif), documents (pdf|docx), or other.
  4. Use =~ to check that $1 looks like a date YYYY-MM-DD.
✎ Check your understanding

1.In Bash, which exit code counts as "true" in an if?

2.What's wrong with if [[$x -gt 5]]; then?

3.Which test is true when a directory exists?

4.How do you compare numbers correctly?

← Input, output and redirection