0

I have to write very simple script. It should take 2 args -h and -q. Both are optional, -h can be somewhere. So, -h -q should does the same action like -q -h. If I pass -a ,or -a -a -a - an error should occurs (I mean exit 1). If I pass -a -h -a -a -b.... - it should return "I couldn't recognize -a" + invoke help case. So -h has priority. Could you help me?

while getopts "hq" OPTION
do
case $OPTION in
  h)
     echo "Help here!" ;
     exit 0;
     
esac
done
shift $(($OPTIND - 1))

while getopts "hq" OPTION
do
case $OPTION in
  q) #quiet - return 0, do nothing. 
     exit 0;;
 

                   
  *) #If -a or sth
     echo "I couldn't recognize args" 
     echo "Help here" 
     exit 1
     ;;
     
esac
     
done

1 Answers1

0

This is the correct implementation:

#!/usr/bin/env bash

while getopts :hq OPTION
do  
    case $OPTION in
    h) echo "Help here!" ;
       exit 0;;
    q) echo "quiet do nothing."
       exit 0;;
    ?) echo "I couldn't recognize option [$1]" 
       exit 1;;
    esac
done
shift $((OPTIND - 1))

Note :hq and ?) to process incorrect options (-a -b ...)

Philippe
  • 20,025
  • 2
  • 23
  • 32