Control flow statements are the backbone of decision-making in Bash scripts. They allow scripts to respond to conditions and iterate actions, making automation powerful and efficient.
Control flow directs the sequence in which instructions are executed. Think of it as a roadmap guiding your script through decisions (using if/else) or repeating actions (using loops).
#!/bin/bash
read -p "Enter a number: " num
# Input validation
if ! [[ "$num" =~ ^-?[0-9]+$ ]]; then
echo "Invalid input. Please enter an integer."
exit 1
fi
echo "You have entered the number $num"
if [ $num -gt 0 ]; then
echo "The number is positive."
elif [ $num -lt 0 ]; then
echo "The number is negative."
else
echo "The number is zero."
fiEnter a number: abc
Invalid input. Please enter an integer.
Enter a number: -5
You have entered the number -5
The number is negative.
Enter a number: 0
You have entered the number 0
The number is zero.
vim control_flow.shchmod +x control_flow.sh./control_flow.sh| Issue | Cause | Solution |
|---|---|---|
Permission denied |
Missing execute permission | Run: chmod +x control_flow.sh |
| No output | read input not used correctly |
Ensure echo $num is included for feedback |
| Numeric test error | Using == instead of -eq, etc. |
Use -eq, -gt, -lt, -ge, -le for numbers |
| Script crashes with non-numeric input | Invalid input used in test | Add input validation with regex check |
#!/bin/bash
for name in Alice Bob Charlie; do
echo "Hello, $name!"
donefor i in {1..5}; do
echo "Iteration $i"
donefor (( i=0; i<5; i++ )); do
echo "Number $i"
doneif [ condition ]; then
# commands
elif [ condition ]; then
# commands
else
# commands
fifor item in item1 item2; do
# commands
donefor (( init; condition; increment )); do
# commands
doneUse set -x to trace script execution:
#!/bin/bash
set -x
# your script here
set +xThis helps you see each command as it's executed, aiding troubleshooting.
Add a numeric check to prevent invalid input:
if ! [[ $num =~ ^-?[0-9]+$ ]]; then
echo "Invalid input: Not a number"
exit 1
fiYou’ve learned how to:
- Use
if,elif, andelseto make decisions - Use
forloops to automate repeated tasks - Validate user input and prevent script errors
- Write readable, executable, and traceable scripts
Control flow turns a basic script into a responsive, intelligent automation tool.


