Shell Functions  «Prev  Next»
Lesson 5A script that uses functions
Objective Write a script that uses multiple functions.

Script that uses Multiple Functions

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.

Shell script that uses multiple functions.

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:
  1. welcome Function
    • Displays a welcome message to the user.
  2. check_disk_space Function
    • Uses the df -h command to display the disk space usage in a human-readable format, filtering mounted partitions.
  3. 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.
  4. 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.

Using functions versus using Other 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:

Using the separate script method

Advantages Disadvantages
  1. You can run a script without running the script that calls it. This means you can debug your code one script at a time.
  2. An error in one of your scripts won’t affect the lines of code in the other scripts.
  3. You can use the ls command to see a list of your scripts.
  1. Copying your script to another computer involves copying multiple files. If you miss one file, your program won’t fully work.
  2. Scripts have more memory and CPU overhead, so they will run slower than functions.
  3. You cannot see variables created in scripts that you call.

The next lesson describes sharing data with a function.

Script uses Functions - Exercise

Click the Exercise list to sort a set of function definitions and calls into correct order.
Script uses Functions - Exercise

SEMrush Software 5 SEMrush Banner 5