- Published on
Exposing Bash Script Functions and calling them in a Makefile Target
- Authors
- Name
- Yair Mark
- @yairmark
Today I wrote bash file with a bunch of functions in that I wanted to use in a makefile. I did this to automate a manual process I had to test some code.
Exposing these bash functions ended up being trivial as described in this question.
All you have to do is add "$@"
as the last line of your bash script.
The answer to this question has the following example script file called test.sh
:
testA() {
echo "TEST A $1";
}
testB() {
echo "TEST B $2";
}
"$@"
Assuming these are in a file called test.sh
we can run the above as follows:
./test.sh testA
>> TEST A
./test.sh testA arg1 arg2
>> TEST A arg1
./test.sh testB arg1 arg2
TEST B arg2
As per this question's answer, this script can be further enhanced by adding a helpful message if the function provided does not exist:
testA() {
echo "TEST A $1";
}
testB() {
echo "TEST B $2";
}
if declare -f "$1" > /dev/null
then
# call arguments verbatim
"$@"
else
# Show a helpful error
echo "'$1' is not a known function name" >&2
exit 1
fi
Using this in a makefile is actually really easy:
test-a-no-params:
cd scripts && ./test.sh testA
test-a-with-params:
cd scripts && ./test.sh testA arg1 arg2
test-b-with-params:
cd scripts && ./test.sh testB arg1 arg2