Intermediate · 10 min · practise every command in the built-in terminal

Conditionals in Bash

Basic if/else

#!/bin/bash
if [ condition ]; then
    # commands
elif [ other_condition ]; then
    # commands
else
    # commands
fi

String comparisons

NAME="IVski"

if [ "$NAME" = "IVski" ]; then
    echo "Hello, IVski!"
fi

if [ "$NAME" != "guest" ]; then
    echo "Not a guest"
fi

if [ -z "$NAME" ]; then      # Empty string
    echo "Name is empty"
fi

if [ -n "$NAME" ]; then      # Non-empty string
    echo "Name is set"
fi

Numeric comparisons

AGE=25

if [ $AGE -gt 18 ]; then echo "Adult"; fi
if [ $AGE -lt 18 ]; then echo "Minor"; fi
if [ $AGE -eq 25 ]; then echo "Exactly 25"; fi
if [ $AGE -ne 30 ]; then echo "Not 30"; fi
if [ $AGE -ge 18 ]; then echo "18 or older"; fi

File tests

if [ -f file.txt ]; then echo "Is a file"; fi
if [ -d directory ]; then echo "Is a directory"; fi
if [ -e path ]; then echo "Exists"; fi
if [ -r file ]; then echo "Readable"; fi
if [ -w file ]; then echo "Writable"; fi
if [ -x file ]; then echo "Executable"; fi
if [ -s file ]; then echo "Non-empty file"; fi

Combining conditions

if [ $AGE -gt 18 ] && [ $AGE -lt 65 ]; then
    echo "Working age"
fi

if [ "$USER" = "root" ] || [ "$USER" = "admin" ]; then
    echo "Privileged user"
fi

Modern double brackets [[ ]]

if [[ "$NAME" == IVsk* ]]; then    # Glob matching
    echo "Starts with IVsk"
fi

if [[ "$NAME" =~ ^[A-Z] ]]; then   # Regex matching
    echo "Starts with uppercase"
fi

Practice tasks

  1. Write a script that checks if README.txt exists and prints a message
  2. Write a one-liner that checks whether the documents directory exists
  3. Check whether a variable is empty using -z

Commands in this lesson

Shell Scripting