Bash: If-Statements
The `if-statement` allows your script to make decisions based on whether a condition is true or false.
Basic If-Statement
Conditional check
if [ "$1" == "hello" ]; then
echo "The argument is hello"
fi
The `if` block is a basic conditional check. If the condition inside the brackets is true, the commands inside the `then` block are executed.
If-Else-Statement
Using else for a fallback
if [ "$1" == "hello" ]; then
echo "Hello, world!"
else
echo "I do not recognize that."
fi
The `else` statement provides a fallback block of code that runs if the initial `if` condition is false.
If-Elif-Else-Statement
Multiple conditions
if [ "$1" == "hello" ]; then
echo "Hello."
elif [ "$1" == "goodbye" ]; then
echo "Goodbye."
else
echo "I do not know that command."
fi
The `elif` (else if) statement allows you to check for multiple conditions in a single block.
Conditional Operators
Numeric comparisons
# Greater than
if [ "$1" -gt 10 ]; then
echo "Greater than 10"
fi
# Less than or equal to
if [ "$1" -le 10 ]; then
echo "Less than or equal to 10"
fi
| Operator | Description |
|---|---|
-eq | Equal to |
-ne | Not equal to |
-gt | Greater than |
-ge | Greater than or equal to |
-lt | Less than |
-le | Less than or equal to |
File and directory checks
# Check if a file exists
if [ -e "/path/to/file.txt" ]; then
echo "File exists"
fi
# Check if a directory exists
if [ -d "/path/to/directory" ]; then
echo "Directory exists"
fi
| Operator | Description |
|---|---|
-e | File or directory exists |
-f | Is a regular file |
-d | Is a directory |
-s | File is not empty |
-r | File has read permission |
String patterns
if [[ "$1" == start* ]]; then
echo "String starts with 'start'"
fi
Use double brackets `[[ ... ]]` for pattern matching with wildcards like `*`.