Exploring the Behavior of Sourcing Bash Scripts in Function Calls

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.

?? Danil Golubintsev

DevOps/MLOps/SRE engineer | 5+ years | Cloud Infrastructure, Automation, and CI/CD Expert | AWS, Kubernetes, Terraform, Ansible

4 个月

Very helpful!

回复

要查看或添加评论,请登录

Adel ?? Tankado的更多文章

  • Existence of PID 0 in Linux

    Existence of PID 0 in Linux

    We all know about PID 1 in Linux—the main initialization process that starts everything during the operating system…

    7 条评论
  • Tabbed windows as i3 in Hyprland

    Tabbed windows as i3 in Hyprland

    ?? The one thing I really missed when switching from i3 to #hyprland is window grouping. I don’t understand why so many…

    5 条评论
  • Screenshots are not simple in Linux

    Screenshots are not simple in Linux

    Today I spent three hours on yet another round of troubleshooting in Linux to make it do simple things once again. I…

社区洞察

其他会员也浏览了