Function Exit Status Codes
Scripts use exit to define exit status codes and terminate executoin.
Functions use return to define exit status codes and terminate execution.
#!/bin/bash
# Function with conditional exit status
check_file() {
if [ -f "/etc/hosts" ]; then
echo "File exists"
else
return 2
fi
}
check_file
echo $?
Parameterized Functions
Functions can accept parameters passed during invocation:
#!/bin/bash
greet_user() {
echo "Hello $1"
}
greet_user $1
Multiple parameters example:
#!/bin/bash
greet_multiple() {
echo "Hello $1 $2"
}
greet_multiple $1 $2
Positional Parameters in Functions
Funtcions hendle all positional parameters using special variables:
#!/bin/bash
display_params() {
echo "Script name: $0"
echo "Parameter count: $#"
echo "First parameter: $1"
echo "All parameters: $*"
echo "Exit status: $?"
}
display_params $*
Case Statement Syntax
Case statements provide pattern matching for conditional execution:
#!/bin/bash
case "$1" in
"start"|"START")
echo "Service started"
;;
"stop"|"STOP")
echo "Service stopped"
;;
*)
echo "Invalid command"
;;
esac
Character Type Detection
Use case statements to identify character types:
#!/bin/bash
case "$1" in
[0-9])
echo "Digit detected: $1"
;;
[a-zA-Z])
echo "Letter detected: $1"
;;
*)
echo "Invalid input"
exit 1
;;
esac
Menu Systems with Case
Convert menu systems to use case statements for cleaner logic:
#!/bin/bash
# Check script files
check_lamp=`[ -s /server/scripts/lamp.sh ] && echo valid || echo invalid`
check_lnmp=`[ -s /server/scripts/lnmp.sh ] && echo valid || echo invalid`
# Validate executables
case "$check_lamp" in
valid)
echo -e "\033[32mLAMP script executable\033[0m"
;;
*)
echo -e "\033[31mLAMP script not executable!\033[0m"
;;
esac
cat << EOF
$(echo -e "\033[35m (1).[install lamp]\033[0m")
$(echo -e "\033[36m (2).[install lnmp]\033[0m")
$(echo -e "\033[33m (3).[exit]\033[0m")
EOF
read -p "Select option: " choice
case "$choice" in
1)
echo "Installing LAMP..."
/server/scripts/lamp.sh
;;
2)
echo "Installing LNMP..."
/server/scripts/lnmp.sh
;;
3)
echo "Exiting..."
exit
;;
*)
echo "Invalid selection"
exit 1
;;
esac
Nginx Service Management
Create comprehensive Nginx management using case and functions:
#!/bin/bash
start_nginx() {
nginx
echo "Nginx started successfully"
}
stop_nginx() {
if [ $(ss -lntup | grep nginx | wc -l) -eq 0 ]; then
echo "Nginx already stopped"
else
pkill nginx
echo "Nginx stopped"
fi
}
restart_nginx() {
stop_nginx
sleep 1
start_nginx
echo "Nginx restarted"
}
case "$1" in
start)
start_nginx
;;
stop)
stop_nginx
;;
restart)
restart_nginx
;;
*)
echo "Usage: $0 {start|stop|restart}"
exit 1
;;
esac
While Loop Constructs
While loops execute commands as long as conditions remain true:
#!/bin/bash
# Sum numbers from 1 to 100
number=0
sum=0
while [ $number -lt 100 ]; do
let number++
let sum=$sum+$number
done
echo "Sum: $sum"
File Processing with While
Process files line by line:
#!/bin/bash
# Calculate average from age file
sum_age=0
count=0
while read -r current_line; do
individual_age=$(echo $current_line | awk '{print $2}')
let sum_age=$sum_age+$individual_age
let count++
done < age.txt
average=$(echo "$sum_age/$count" | bc)
echo "Average age: $average"
Interactive Menus with While
Create persistent menus using infinite loops:
#!/bin/bash
while true; do
cat << MENU
$(echo -e "\033[32m 1. Option A\033[0m")
$(echo -e "\033[33m 2. Option B\033[0m")
$(echo -e "\033[34m 3. Exit\033[0m")
MENU
read -p "Choose option: " selection
case $selection in
1)
echo "Selected option A"
;;
2)
echo "Selected option B"
;;
3)
echo "Goodbye"
exit 0
;;
*)
echo "Invalid choice, try again"
;;
esac
done
Number Guessing Game
Implement interactive games with while loops:
#!/bin/bash
# Generate random number
target=$((RANDOM % 100 + 1))
attempts=0
echo "Guess the number between 1-100!"
while true; do
read -p "Enter your guess: " guess
# Validate input
if ! [[ "$guess" =~ ^[0-9]+$ ]]; then
echo "Please enter a valid number"
continue
fi
let attempts++
if [ $guess -eq $target ]; then
echo "Correct! Number was $target"
echo "Attempts: $attempts"
break
elif [ $guess -gt $target ]; then
echo "Too high!"
else
echo "Too low!"
fi
done
System Information Menu
Create comprehensive system monitoring tools:
#!/bin/bash
while true; do
cat << INFO_MENU
$(echo -e "\033[32m [h]. Help\033[0m")
$(echo -e "\033[32m [f]. Login info\033[0m")
$(echo -e "\033[32m [d]. Disk info\033[0m")
$(echo -e "\033[32m [m]. Memory usage\033[0m")
$(echo -e "\033[32m [u]. System load\033[0m")
$(echo -e "\033[35m [q]. Quit\033[0m")
INFO_MENU
read -p "Select option: " option
case $option in
h)
echo "System information menu"
sleep 2
clear
;;
f)
echo "Active sessions: $(who | wc -l)"
who
;;
d)
df -h
;;
m)
free -h
;;
u)
uptime
;;
q)
echo "Goodbye!"
exit 0
;;
*)
echo "Invalid option"
;;
esac
done