Solution:
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
main "$@"
fi
I added this answer because I wanted an answer that was written in a style to mimic Python’s if __name__ == '__main__' but in Bash.
Regarding the usage of BASH_SOURCE vs $_. I use BASH_SOURCE because it appears to be more robust than $_ (link1, link2).
Here is an example that I tested/verified with two Bash scripts.
script1.sh with xyz() function:
#!/bin/bash
xyz() {
echo "Entering script1's xyz()"
}
main() {
xyz
echo "Entering script1's main()"
}
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
main "$@"
fi
script2.sh that tries to call function xyz():
#!/bin/bash
source script1.sh
xyz