Search code examples
bashshellunixgetopts

how to use getopt/getopts


So, I've learned how to pass in arguments in my bash script. The next step for me is to pass in a flag with the argument. For example,-id 12345, -d YES or -d NO, -h localhost.

So, I'm looking to execute like so: ./Build.sh -id 12345 -d YES -h localhost

Currently, I'm doing it this way: ./Build.sh 12345 YES localhost

Is getopt, getopts what I'm after? If so, can you show me how I use this with my script?

My working script thus far:

if [[ $# != 3 ]]; then
   echo "Usage: ./Build.sh <CUSTID> <YES|NO> <HOST>" 2>&1
   exit 1
fi

# Checks for YES or NO option for Create.sql script
case $2 in
    YES|NO)
       filename="Build_$2.sql"
       ;;
    *)echo "Must enter YES or NO"
      exit 1
      ;;
esac

Solution

  • #!/bin/bash
    
    script="$0"
    usage() {
      echo "Usage: $script <CUSTID> <YES|NO> <HOST>" 1>&2;
      exit 1;
    }
    
    while getopts ":i:d:h:" o; do
      case "${o}" in
        i)
          i=${OPTARG}
          ;;
        d)
          d=${OPTARG}
          if [[ "$d" != YES && "$d" != NO ]]; then
            usage
          fi
          ;;
        h)
          h=${OPTARG}
          ;;
        *)
          usage
          ;;
      esac
    done
    shift $((OPTIND-1))
    
    if [[ -z "$i" || -z "$d" || -z "$h" ]]; then
      usage
    fi
    
    echo i: $i, d: $d, h: $h, rest: $@
    

    However, -h is by convention reserved for "help"; you may or may not wish to change it.