2

I'm trying to use getops in a function yet it doesn't seem to work:

#!/bin/bash

function main()
{
  while getopts ":p:t:c:b:" o; do
    case "${o}" in
    p)
      echo "GOt P"
      p=$OPTARG
      ;;
    t)
      echo "GOt T"
      t=$OPTARG
      ;;
    c)
      echo "GOt C"
      c=$OPTARG
      ;;
    b)
      echo "GOt b"
      b=$OPTARG
      ;;
    *)
      #usage 
      echo "Unknown Option"
      return 
      ;;
      esac
  done

  echo $p
  echo $t
  echo $c
  echo $b
}

main

And then running it like this:

$ ./bin/testArguments.sh -p . -t README.md -c 234 -b 1

I have tried making sure that optid are local yet this didn't work either. Anything else that might be wrong?

galoget
  • 349
Dean
  • 133

2 Answers2

12

You're not passing any argument to your main function. If you want that function to get the same arguments as passed to the script, pass them along with:

main "$@"

Instead of:

main

Also relevant to your script:

1

In a function, the parameters are those passed to the function, not those passed to the script:

$ cat foo.sh
function main ()
{
    echo "$@"
}

echo "$@"
main
$ bash foo.sh bar
bar

$

You need to pass "$@" to main:

main "$@"

Though I find a main function in scripts rather useless, unless you plain to call main again and again in the same script.

Olorin
  • 4,656