1

How can I pass parameters to a script like that:

scriptname.ksh -p param1 -n param2 

I mean how can I tell my script to work with two parameters defined by -p and -n characters?

0

1 Answer 1

6
while getopts ":p:n:" Option; do
  case $Option in
    p)
      # do stuff
      # to access param1, use variable $OPTARG
      ;;
    n)
      # do stuff
      # $OPTARG again to access param2
      ;;
    \?)
      # default
      ;;
  esac
done
shift $(($OPTIND - 1))

In the first argument to getopts:

  • leading : supresses getopts's own internal error reporting
  • letters indicate options
  • if a letter is followed by a :, it means it expects an $OPTARG

more information

getopts provides faculties for changing the name of the option argument variable.

note that getopts cannot process "long-form" arguments (--help etc.)

Sign up to request clarification or add additional context in comments.

1 Comment

I would add a "default" branch to the case statement: ?) error "invalid option: -$OPTARG"; show_help; exit 1 ;;

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.