2

I'm fairly new to bash scripting, and wondered what's the simplest way to make bash script functions in a script as the parameter when run via command line?

Example usage:

./myscript function1
./myscript function2

Example contents of myscript:

echo "Example myscript"

function1() { 
    echo "I am function number 1"
}

function2() { 
    echo "I am function number 2"
}

if [ $# -eq 0 ]; then
    echo "Specify a function. E.g. function1"
    exit 1;
fi

The script would only execute the specific function when called for on command line otherwise would show some example usage. It would need to be usable by cron and such processes as well as executed by a user.

  • Would a case statement be suitable? – James White Apr 30 '15 at 14:35
5

All arguments passed to shell script was stored in $@, you can loop through them:

#!/bin/bash

echo "Example myscript"

function1() { 
    echo "I am function number 1"
}

function2() { 
    echo "I am function number 2"
}

if [ $# -eq 0 ]; then
    echo "Specify a function. E.g. function1"
    exit 1;
fi

for func do
  [ "$(type -t -- "$func")" = function ] && "$func"
done

[ "$(type -t -- "$func")" = function ] make sure that we only make function call when $func is function.

Example:

$ ./test.sh function1
Example myscript
I am function number 1

$ ./test.sh function1 function2
Example myscript
I am function number 1
I am function number 2
  • 1
    (and you can use [ "$(type -t -- "$func")" = function ] if you want to check that $func is a function first (though it won't tell the difference between functions defined in the file and functions imported from the environment)). – Stéphane Chazelas Apr 30 '15 at 15:22
  • @StéphaneChazelas: Good point! Updated my answer. – cuonglm Apr 30 '15 at 15:28
  • Thanks, upvoted, but I think it would be perfect if you also add echo "function... doesn't exit" in case user enters an invalid parameter like "function3" (or anything else?). – Sadi Dec 6 '15 at 15:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.