1

I'm trying to get it to call a function.

Here is my code

#!/bin/bash
while getopts ":a:b:" opt; do
    case $opt in 
        a)
            my_function "%e"
            ;;
        b)
            my_function "%s"
            ;;
       /?)
            echo "Invalid option: -$OPTARG"
            ;;
    esac
done

my_function() {
    option=$1
    //do something here
}

When i call: ./myscript.sh -a sshd

This would display ./myscript.sh: line 5: my_function: command not found

What should I do to fix it?

Jay Lee
  • 13

1 Answers1

1

For a shell script to be able to call a function, that function has to have been defined before calling it. This is not the case in your code.

To fix it, move the function to above the command line parsing loop.

Also, I would make the last case test be *) to catch any unhandled option (/? would never match a single option character). And the getopts utility would already output an error message, so you don't need to repeat that ($OPTARG may additionally not be what you use here, but $opt).

Kusalananda
  • 333,661