1

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?

4

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.

|improve this answer|||||
0

Short Answer Yes

Long Answer If you source a script, it is the same as executing a script, but in your own shell process. Thus environment variables, function names, etc are shared. See https://superuser.com/a/176788/222230

|improve this answer|||||
  • Is there any solution without renaming the main function? – Nikhil Nov 6 '19 at 21:00
  • yes, 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. – Till Schäfer Nov 6 '19 at 21:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.