Yes, it is entirely possible and often a good practice to modularize a big bash script into smaller, more manageable files. This makes the script easier to maintain, test, and reuse. Here’s how you can structure and use smaller files within a bash script:


1. Splitting the Script

Divide your script into logical components or functions, and save each in a separate file. For example:

  • main_script.sh: The main script.
  • utilities.sh: Helper functions.
  • config.sh: Configuration variables.

2. Sourcing Other Files

You can “include” another file in your script using the source or . command:

#!/bin/bash

# Source external files
source ./utilities.sh
source ./config.sh

# Use functions and variables from sourced files
greet_user "Alice"
echo "Config value: $CONFIG_VALUE"
  • source ./file.sh or . ./file.sh loads and executes the file’s content in the current shell.

3. Example: Modularized Script

main_script.sh (Main File)

#!/bin/bash

# Source helper scripts
source ./utilities.sh
source ./config.sh

# Main logic
echo "Starting the script..."
greet_user "Alice"
echo "Config value is: $CONFIG_VALUE"

utilities.sh (Utility Functions)

#!/bin/bash

# Function to greet a user
greet_user() {
    echo "Hello, $1!"
}

config.sh (Configuration File)

#!/bin/bash

# Configuration variables
CONFIG_VALUE="MyConfigValue"

4. Advantages of Modularization

  • Improved Readability: Each file serves a single purpose.
  • Reusability: Functions or configurations can be reused across multiple scripts.
  • Easier Debugging: Smaller files make it easier to isolate and fix issues.

5. Ensure Modular Files Are Readable

  1. Make sure the files being sourced are in the correct location.
  2. Use relative paths (./) or absolute paths (/home/user/...) for clarity.
  3. Check file permissions to ensure they are readable:
    chmod +r utilities.sh config.sh
    

6. Dynamic Inclusion

If you have a variable list of files to include, you can use a loop:

#!/bin/bash

# Include all .sh files in the scripts directory
for script in ./scripts/*.sh; do
    source "$script"
done

7. Testing Modular Scripts

  • Standalone Testing: You can test individual files like utilities.sh by executing them in isolation or running their functions directly.
  • Integration Testing: Run main_script.sh to ensure all modules work together.