Modulinos In Bash

submited by
Style Pass
2021-06-16 04:30:03

A modulino is a file which behaves like a library when it is imported, and like a script when executed. I first read about them in Mastering Perl, but you can create them in other languages too. Here’s how to do it in Bash.

A common refactor with scripts is to encapsulate all the code behavior in functions. As this script only does one thing, it’s a small change:

The line hello "$@" calls the hello function, passing any command line arguments the script received. I’ve added an if clause to use the first function argument if it’s not empty, else to default to “World!” and preserve the original behavior.

This checks that the BASH_SOURCE variable (the script name) equals $0 which is the name of the file invoking the code. These values match when the script is invoked like a program: ./hello.bash. But when the script is sourced $0 evaluates to /bin/bash.

This can be useful if you’d like to be able to import your script code into other scripts via source. One reason to do that is unit testing your scripts:

Leave a Comment