Sourced Bash script, each with main function
The other script will redefine main()
, yes. Though in this particular case, I'm not sure if it matters, since the main()
from script A is running when script B redefines the function. I doubt a shell would allow the redefinition to change the behavior of an already-running function.
That is, given these scripts:
$ cat a.sh
main() {
echo a1
. ./b.sh
echo a2
}
main "$@"
$ cat b.sh
main() {
echo b
}
main "$@"
running a.sh
with any shell I can find prints a1
, b
, a2
. If a.sh
were to call main
again, then it would get the new behaviour, of course.
But even if it doesn't matter here, redefining functions on the fly like that would at least be really confusing.
The better question is, why do you need to source script B in the first place? It would seem clearer to have B as either a collection of functions to be loaded by sourcing, a library of sorts; or to have it as an independent utility, called as a regular program, not sourced.
In the first case, A would explicitly call the functions defined in A as needed.
Related videos on Youtube
Porcupine
Updated on September 18, 2022Comments
-
Porcupine over 1 year
I am using Bash 4.4.20. I typically have main function in each bashscript. If I want to source this script from another function inside another bash script, will this conflict with the main function definition in both the scripts?
#A.sh main() { SomeFunction } SomeFunction(){ . B.sh } main "$@"
#B.sh main(){ echo Hi } main "$@"
Is there any solution without renaming the main function?
-
Porcupine over 4 yearsIs there any solution without renaming the main function?
-
Till Schäfer over 4 yearsyes, but its kind of hackish: see unix.stackexchange.com/a/9726/68290. You should ask yourself if you really want to source that file and not just execute it.