Is it possible to pass options (not params) to a function in bash?

69 Views Asked by At

It would look something like the following:

my_functions(){
  while getopts ":a" Option
    do
      case $Option in
        a ) echo "a" ;;
        * ) ;;
      esac
    done
}

Then you would call it with:

function -ab 

Is this possible or is there a better way to do it?

1

There are 1 best solutions below

0
On BEST ANSWER

The syntax is correct, but this specific example suffered from a poor choice for the function name. This should do it:

f(){

while getopts ":a" Option
do
    case $Option in
    a ) echo "a" ;;
    * ) ;;
    esac
done
shift $((OPTIND -1))

}