Learn BASH with Real Code Examples
Updated Nov 19, 2025
Code Sample Descriptions
1
Bash Counter and Theme Toggle
count=0
isDark=0
updateUI() {
echo "Counter: $count"
echo "Theme: $( [ $isDark -eq 1 ] && echo 'Dark' || echo 'Light' )"
}
increment() { count=$((count + 1)); updateUI; }
decrement() { count=$((count - 1)); updateUI; }
reset() { count=0; updateUI; }
toggleTheme() { isDark=$((1 - isDark)); updateUI; }
# Simulate actions
updateUI
increment
increment
toggleTheme
decrement
reset
Demonstrates a simple counter with theme toggling using Bash variables and console output.
2
Bash Simple Calculator
add() { echo $(( $1 + $2 )); }
subtract() { echo $(( $1 - $2 )); }
multiply() { echo $(( $1 * $2 )); }
divide() { echo $(( $1 / $2 )); }
echo "Add 5 + 3: $(add 5 3)"
echo "Subtract 5 - 3: $(subtract 5 3)"
echo "Multiply 5 * 3: $(multiply 5 3)"
echo "Divide 6 / 2: $(divide 6 2)"
Performs basic arithmetic operations using functions.
3
Bash Factorial
factorial() {
if [ $1 -le 1 ]; then
echo 1
else
echo $(( $1 * $(factorial $(( $1 - 1 ))) ))
fi
}
echo "Factorial of 5: $(factorial 5)"
Recursive factorial calculation.
4
Bash Fibonacci Sequence
fibonacci() {
if [ $1 -eq 0 ]; then
echo 0
elif [ $1 -eq 1 ]; then
echo 1
else
echo $(( $(fibonacci $(( $1 - 1 ))) + $(fibonacci $(( $1 - 2 ))) ))
fi
}
for i in {0..9}; do
echo $(fibonacci $i)
done
Generate Fibonacci numbers using recursion.
5
Bash Array Comprehension Simulation
numbers=(1 2 3 4 5 6 7 8 9 10)
squares=()
for n in "${numbers[@]}"; do
if [ $((n % 2)) -eq 0 ]; then
squares+=( $((n * n)) )
fi
done
echo "${squares[@]}"
Create array of squares for even numbers.
6
Bash String Manipulation
str="HelloWorld"
sub=${str:0:5}
len=${#str}
echo "Substring: $sub, Length: $len"
Demonstrates substring extraction and length.
7
Bash Loop and Conditional
for i in {1..10}; do
if [ $((i % 2)) -eq 0 ]; then
echo "$i is even"
fi
done
Loop through numbers and print even ones.
8
Bash Functions with Arguments
greet() {
echo "Hello, $1!"
}
greet Alice
greet Bob
Pass arguments to functions and print results.
9
Bash Sum of Array
numbers=(1 2 3 4 5)
sum=0
for n in "${numbers[@]}"; do
sum=$((sum + n))
done
echo $sum
Sum elements of an array using a loop.
10
Bash Zip Simulation
arr1=(1 2 3)
arr2=(4 5 6)
for i in ${!arr1[@]}; do
echo "$((arr1[i] + arr2[i]))"
done
Combine two arrays element-wise using a loop.