Exploring the Behavior of Sourcing Bash Scripts in Function Calls
In one of my recent projects, I had to write a Bash script divided into several modules. This raised an important question: when we include Bash scripts using source, does it reopen or reread the files each time we call the functions?
To understand this better, we can utilize the strace tool to observe the inner workings of the code.
Consider the following script containing a simple function:
my_func.sh
#!/bin/bash
my_func() {
echo "Hello World!"
}
We also have a main script that calls this function:
my_script.sh
#!/bin/bash
source ./my_func.sh
my_func
my_func
Don't forget to give execution rights to your script:
chmod +x my_script.sh
Next, we can run the script under strace to monitor system calls related to file operations:
strace -e trace=openat ./my_script.sh
The output should look something like this:
openat(AT_FDCWD, "./my_script.sh", O_RDONLY) = 3
openat(AT_FDCWD, "./my_func.sh", O_RDONLY) = 3
This indicates that, in the context of my_script.sh, the file containing the function definitions my_func.sh was read only once. If my_func.sh were being read anew each time the function was called, we would expect to see more openat(AT_FDCWD) entries than just two.
Conclusion:
When executing a script that includes functions from another file, the included file is only read once, regardless of how many times the functions are invoked. This finding highlights the efficiency of using source to include Bash scripts, as it minimizes unnecessary file access during execution.
DevOps/MLOps/SRE engineer | 5+ years | Cloud Infrastructure, Automation, and CI/CD Expert | AWS, Kubernetes, Terraform, Ansible
4 个月Very helpful!