Cleaner BASH Scripting with a Main Function
-
BASH is not one of the prettiest languages out there and any attempt at serious coding with it can result in premature balding and serious gut rot. Yet BASH is a highly useful and very portable language. It’s available on any UNIX platform and pretty much any UNIX admin will be able to maintain your code. So while it is very limiting, it has very good use cases. It is anything but popular, but popular is rarely the right choice when it comes to code.
One means of cleaning up BASH code to make it behave more like a more modern, advanced language is adding in an entry point via a “main” function. The trick here is to make this the very last function in your script and to use the stub code that I provide below. By doing this, you can put all of your main routine in one, easy to find place and you can keep all of your script in functions making it vastly easier to read and maintain. This little trick did wonders for cleaning up my code and now if I am doing a script of any size I do this straight away.
main() { } main "$@"
Originally found in 2014 on my Linux blog here: http://web.archive.org/web/20140825114908/http://www.scottalanmiller.com/linux/2014/08/21/better-scripting-with-bash/
exit