An example of how a larger bash script can be splitted into into multiple files
Entrypoint ./src/main.sh:
print_foo "foo"
print_bar "bar"
Module #1 ./lib/print_bar.sh:
function print_bar() {
echo "bar: $1"
}
Module #2 ./lib/print_foo.sh:
function print_foo() {
echo "foo: $1"
}
Resulting file: ./target.sh:
#!/usr/bin/env bash
function main() {
print_foo "foo"
print_bar "bar"
}
function print_bar() {
echo "bar: $1"
}
function print_foo() {
echo "foo: $1"
}
main $@
- Put the main part of your project into the ./src/main.sh file. It will be the entrypoint for your script;
- Move all your function declarations into the modules under the
./libdirectory (./lib/print_bar.sh and ./lib/print_foo.sh in this example); - Copy the content of the Makefile to the root of your project;
- Replace the value of the variable
TARGET_FILEin theMakefile(wich istarget.shby default) with the name that your prefer; - Run
makefrom your project directory; - The content of your
main.shfile will be wrapped into themainfunction and will be invoked at the end of the script, so all of the functions defined in modules under thelibdirectory will be available in it;