Search code examples
shellgetoptgetopts

Shell script getopts optarg no value


Could someone examine this code snippet and tell me why when I call this script with a -p abcdef that $OPTARG never has the passed in argument value?

# Process command-line options passed as switches to this script
while getopts "ph:" option; do
  case "$option" in
    p)
       {
         if [ -n "$OPTARG" ]; then
           echo
           echo "##### SCRIPT ERROR: You failed to provide a host prefix. #####"
           echo
           usage
           break
         else
           echo "Setting host prefix to '$OPTARG'"
           echo
           HOST_PREFIX=$OPTARG
         fi
       } ;;
    h) usage ;;
    '?') usage ;;
    *) break ;;
  esac
done
shift "$((OPTIND-1))" # Shift off the options and optional --.

Solution

  • All options that requires arguments must be succeeded by :, it should be written as p:h as h option doesn't required arguments.