1

My code:

#options() {
while getopts s:v:h opt; do
  case ${opt} in
    s)
      echo -s passed with ${OPTARG}
      ;;
    v)
      echo -v passed with ${OPTARG}
      ;;
    h)
      usage
      exit
      ;;
    *)
      usage
      exit
      ;;
  esac
done
#}
#options

If I call it in a script everything works as expected. But as soon as I remove the hashes and make a function of the code I never get into the case marks.

Can someone explain this behavior?

EDIT:

The following is my latest insight.

There are 3 possible scopes for variables inside shell scripts:

  1. local
  2. global
  3. "in-main-visible-only" or whatever the exact name is for that scope.
codeforester
  • 39,467
  • 16
  • 112
  • 140
  • 1
    In a function, the `$` arguments refer to the function's args, not the entire script's (command line args). – underscore_d Dec 08 '17 at 12:59
  • 1
    likely duplicate of [Access arguments to Bash script inside a function](https://stackoverflow.com/questions/3966048/access-arguments-to-bash-script-inside-a-function) or [In Bash, how do you access command line arguments inside a function?](https://stackoverflow.com/questions/2740906/in-bash-how-do-you-access-command-line-arguments-inside-a-function) – underscore_d Dec 08 '17 at 12:59
  • 1
    Maybe point out that while the code doesn't *directly* attempt to access the positional parameters, `getopts` certainly does precisely that under the hood. – tripleee Dec 08 '17 at 13:35

0 Answers0