SkillByAIOpen interactive version →

Lesson 25 / 31

Variables & Conditionals

Store values in variables and branch with if, else and file tests in Bash scripts.

Variables

No spaces around =. Read a variable's value with $name.

name="Bob"
count=3
echo "$name has $count files"

Output:

Bob has 3 files

if / else

Test expressions go inside [ ] (spaces matter). -f checks a file exists.

if [ -f "notes.txt" ]; then
    echo "File exists"
else
    echo "Not found"
fi

Output:

File exists