Conditionals

Shell Conditionals

Shell scripts use if/then/else/fi for conditional logic.
bash
#!/bin/bash

# Basic if/else
if [ -f "myfile.txt" ]; then
    echo "File exists!"
else
    echo "File not found"
fi

# String comparison
if [ "$USER" = "root" ]; then
    echo "You are root!"
fi

# Numeric comparison
COUNT=5
if [ $COUNT -gt 3 ]; then
    echo "Count is greater than 3"
fi

Tip:Always put spaces inside [ brackets ]. [ -f file ] is correct, [-f file] will fail.

Terminalbash
Welcome to the Linux Terminal Simulator!
Type commands below. Use 'help' to see available commands.
user@codewithmuh:~$

💬 Got questions? Ask me anything!