mardi 21 novembre 2023

Shell Script Design Patteren: Source a library file VS Call different files?

We discuss about POSIX compliant shell script here.

While we are writing more and more shell scripts, we build some helper functions to reuse the codes.

We are considering putting a few helper functions (around 10 functions of the same category) into a library file (e.g. string_lib.sh) or splitting each functions into individual script files (e.g. str_replace, str_cmp, etc.) to be called directly.

Due to the potential problem of variable name collision, we lean towards splitting each functions into individual script files. But there will be more than a hundred of script files, which is hard to manage.

We understand in some cases, we do not have a choice to choose between these two.

  • If we need to pass (several) variables from functions back to the caller, we must use a library file and sources it, as they need to share the same variable scope. (Using text file to pass variable is not preferred in most cases.)

  • If we would just like to avoid one script file being too long, split it into different sections and source them sequentially. In this case they usually need some shared variables (e.g. setting variables).

In other cases, these would be the pros and cons comparison.

Grouping helper functions into library files:

  • (o) The library file will be sourced (by . string_lib.sh).
  • (+) Same category of functions written in same file. Easy to manage.
  • (-) Possible of variable name collision.
  • (-) Need to avoid double inclusion, or mutual recursive inclusion which will cause infinite loop.
  • (-) Too many inclusion may slower the script. If only a few functions are used within a library file, other function definitions are redundant.

Split functions into individual script files:

  • (o) The script files will be called directly, just like Linux programs.
  • (+) No need to source (i.e. .) before use. Just put all the scripts into the $PATH directory.
  • (+) Unnecessary functions are not sourced. Possibly faster loading.
  • (+) Called script is in a different shell, the sub-shell. No worry of variable name collision. (Similar concept as Java, C, etc.)
  • (-) One helper function will have one script file. There will be many script files. This is harder to manage.

There is another SO answer about bash design patterns and best practices. Especially Stefano Borini's Modularization section is inspiring. Its import function is smartly written. Do take a look when you need to source script files. However in that SO post, it did not compare between grouping functions into a library file versus splitting functions into individual files.

https://stackoverflow.com/a/739034/1884546

Are there any guidelines or recommended design patterns of shell scripts?

Aucun commentaire:

Enregistrer un commentaire