Scripts are often organized by using functions. All tasks that the script performs are copied into functions. At the bottom of the script, the overall controlling loops or commands are included and the functions are called from these statements. To decipher a script written in this fashion, read the code at the bottom of the script, the main program. This gives you a general idea of what the script does. Once you understand this, you can look at the individual functions to see the details of how the tasks are performed.
- Multi-Function
Here's an example shell script that contains two functions, one to square an input and the other to capitalize the first letter of each word:
#!/bin/bash
# Function to square a number
square() {
result=$(echo "$1 * $1" | bc)
echo $result
}
# Function to capitalize the first letter of each word
capitalize() {
echo $* | awk '{for(i=1;i<=NF;i++){$i=toupper(substr($i,1,1)) substr($i,2)};print}'
}
# Main script
# Call the square function with an input of 5
squared=$(square 5)
echo "5 squared is: $squared"
# Call the capitalize function with a string input
capitalized=$(capitalize this is a test string)
echo "Capitalized string: $capitalized"
In this script, the square function takes a single input and uses the bc command to calculate the square of that input. The result is then printed to the console. The capitalize function takes a string input and uses the awk command to capitalize the first letter of each word in the string. The capitalized string is then printed to the console. In the main part of the script, the two functions are called with example inputs and the results are printed to the console. Note that the capitalize function is called with a string input that contains spaces, which are passed as separate arguments to the function using the $* special parameter.
Here's an example of a shell script that uses multiple functions to demonstrate some typical tasks. This script has functions to display a welcome message, check disk space, back up a specified directory, and display the backup status.
#!/bin/bash
# Function to display a welcome message
welcome() {
echo "elcome to the System Maintenance Script"
echo "---------------------------------------"
}
# Function to check disk space
check_disk_space() {
echo "Checking disk space..."
df -h | grep '^/dev/' # Lists disk space for mounted partitions
echo "---------------------------------------"
}
# Function to back up a specified directory
backup_directory() {
local DIR=$1
local BACKUP_DIR="/backup"
local TIMESTAMP=$(date +%Y%m%d_%H%M%S)
# Check if directory exists
if [ -d "$DIR" ]; then
echo "Backing up $DIR to $BACKUP_DIR/$TIMESTAMP.tar.gz..."
mkdir -p "$BACKUP_DIR"
tar -czf "$BACKUP_DIR/${DIR##*/}_$TIMESTAMP.tar.gz" "$DIR"
echo "Backup of $DIR completed."
else
echo "Directory $DIR does not exist. Skipping backup."
fi
echo "---------------------------------------"
}
# Function to display backup status
backup_status() {
local BACKUP_DIR="/backup"
echo "Recent backups in $BACKUP_DIR:"
ls -lh $BACKUP_DIR | tail -n 5
echo "---------------------------------------"
}
# Main script logic
welcome # Call welcome function
check_disk_space # Call check disk space function
# Example usage: back up the /etc directory
backup_directory "/etc" # Call backup directory function
backup_status # Call backup status function
Explanation of the Script:
welcome
Function
- Displays a welcome message to the user.
check_disk_space
Function
- Uses the
df -h
command to display the disk space usage in a human-readable format, filtering mounted partitions.
backup_directory
Function
- Takes a directory path as an argument (
$1
).
- Checks if the specified directory exists and, if it does, backs it up by creating a
.tar.gz
archive in the /backup
directory with a timestamp.
- If the directory doesn’t exist, it skips the backup with a message.
backup_status
Function
- Lists the last five backup files in the
/backup
directory to show recent backup statuses.
Running the Script:
Save the script to a file, e.g., `maintenance.sh`, and make it executable with:
chmod +x maintenance.sh
Then, execute it:
./maintenance.sh
Each function is modular and can be called independently, showcasing how functions enhance readability, reusability, and maintainability in shell scripts.
The course project main script, volleyball, calls scripts that are stored in separate files to perform various tasks. You can take those separate scripts and include them as functions inside the volleyball script instead of implementing them as separate scripts. When should you store a task in a function and when should you store a task in a separate script? It depends on the circumstances. Let us look at a list of the advantages and disadvantages of both methods: