Product SiteDocumentation Site

5.6. Guarding shell scripts against changes

bash only reads a shell script up to the point it is needed for executed the next command. This means that if script is overwritten while it is running, execution can jump to a random part of the script, depending on what is modified in the script and how the file offsets change as a result. (This behavior is needed to support self-extracting shell archives whose script part is followed by a stream of bytes which does not follow the shell language syntax.)
Therefore, long-running scripts should be guarded against concurrent modification by putting as much of the program logic into a main function, and invoking the main function at the end of the script, using this syntax:
main "$@" ; exit $?
This construct ensures that bash will stop execution after the main function, instead of opening the script file and trying to read more commands.