AcademyThe Automator's Grimoire: Scripting WizardryCircle 2: The Flow of Power (Control)

Conditionals in Bash

Scripts need to make decisions. We use if, elif, else, and fi.

Syntax

Bash is very strict about spaces inside the brackets [ ].

#!/bin/bash
if [ -f "config.json" ]; then
    echo "Config file exists!"
else
    echo "Creating default config..."
    touch config.json
fi

Common File Tests

  • -f file: True if file exists and is a regular file.
  • -d dir: True if directory exists.
  • -z string: True if string length is zero.
  • $A -eq $B: True if A equals B (integers).
booting...

Mission Control

Write an if statement

Expected Command

cat check.sh

Test the logic