Course contentsShow
← Linux
Lesson 166 of 1,8192. Deep Dive into Bash ScriptingFree lesson

Dynamic Function Generation

Define and execute functions dynamically based on runtime input.

Dynamic Function Generation

In this lesson, you will learn how to create and execute Bash functions on the fly based on data you receive while your script is running.

Up until now, we have defined functions by hardcoding them into our script files. However, there are scenarios—such as processing configuration files or reacting to external API responses—where you don't know the function names or their logic until the script is actually executing. In Bash, you can achieve this by treating function definitions as strings and evaluating them dynamically.

The eval Approach

To define a function dynamically, you construct the function body as a string and then pass that string to the eval command. The eval command takes a string and tells the shell to treat it as code to be executed.

Consider this example where we create functions based on a list of process names:

services=("backup" "cleanup" "sync")

for name in "${services[@]}"; do
    # Define a function name and logic dynamically
    func_def="function run_${name} { echo 'Executing process: ${name}'; }"
    
    # Evaluate the string to register the function
    eval "$func_def"
done

# Now we can call them as if they were written in the file
run_backup
run_cleanup

Why Use This?

This technique allows your script to adapt its capabilities based on runtime input. Instead of writing massive case statements or long if-elif chains to handle every possible task, you can generate the exact function needed for the current input.

A Word of Caution: Because eval literally executes whatever is inside your string, you must ensure that the input used to generate these function names is sanitized. If a user provides input that becomes part of that string, they could potentially inject malicious commands into your execution environment. Always treat dynamic input as untrusted before passing it to eval.

By using string concatenation to build function definitions and eval to register them, you can build highly flexible scripts that expand their own functionality as they run.

Key Takeaway: Dynamic function generation uses string construction paired with the eval command to register new logic into your script's environment while it is actively running.