What's the difference between sourcing file in global scope and in a function scope?
That is between:
loadlib ()
{
source "$1.sh"
}
loadlib lib
and
source lib.sh
Is there something to worry about, except "local" declarations of variables in lib.sh?
Starting point of this question is the comment "# Since we use some associated arrays, this file should be included from outside a function." from yaourt program.
git clone http://projects.archlinux.fr/yaourt.git
vim ./yaourt/src/lib/util.sh.in
Documentation
from man bash
. filename [arguments]
source filename [arguments]
Read and execute commands from filename in the current shell environment and return the exit status of the last command executed from filename. If filename does not contain a slash, file names in PATH are used to find the directory containing filename. The file searched for in PATH need not be executable. When bash is not in posix mode, the current directory is searched if no file is found in PATH. If the sourcepath option to the shopt builtin command is turned off, the PATH is not searched. If any arguments are supplied, they become the positional parameters when filename is executed. Otherwise the positional parameters are unchanged. The return status is the status of the last command exited within the script (0 if no commands are executed), and false if filename is not found or cannot be read.
The bash man page states:
All other aspects of the shell execution environment are identical between a function and its caller with these exceptions: the DEBUG and RETURN traps (see the description of the trap builtin under SHELL BUILTIN COMMANDS below) are not inherited unless the function has been given the trace attribute (see the description of the declare builtin below) or the -o functrace shell option has been enabled with the set builtin (in which case all functions inherit the DEBUG and RETURN traps), and the ERR trap is not inherited unless the -o errtrace shell option has been enabled.
Variables local to the function may be declared with the local builtin command. Ordinarily, variables and their values are shared between the function and its caller.
Implying 'local' variables and positional parameters to be the only exceptions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With