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
./lib
directory (./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_FILE
in theMakefile
(wich istarget.sh
by default) with the name that your prefer; - Run
make
from your project directory; - The content of your
main.sh
file will be wrapped into themain
function and will be invoked at the end of the script, so all of the functions defined in modules under thelib
directory will be available in it;