Bash getopts doesn't show error for second option

99 views Asked by At

I want a script to take in two options, both are required. if I pass one in, the script doesn't print an error requesting you to pass in a second one.

-bash-4.2$ bash test.sh -b
Invalid option: b requires an argument

-bash-4.2$ bash test.sh -p
Invalid option: p requires an argument

-bash-4.2$ bash test.sh -b sdfsfd

-bash-4.2$ bash test.sh -p sdfsfd

-bash-4.2$ bash test.sh -b sdfsfd -s sfd
Invalid option: s

Code

showHelp()
{
cat << EOF

Find files in client's folder and upload to S3 bucket.

Usage: $(basename $0) [-p PATH_TO_SEARCH] [-b S3 bucket]

OPTIONS:
  -h    Show this help message
  -p    Path to search
  -b    S3 Bucket

EOF
exit 1
}

while getopts ":p:b:h" o; do
    case "${o}" in
        h)
           showHelp
           ;;
        p)
            p=${OPTARG}
            ;;
        b)
            b=${OPTARG}
            ;;
        \? )
            echo "Invalid option: $OPTARG";;
         : )
            echo "Invalid option: ${OPTARG} requires an argument";;
    esac
done
shift $((OPTIND-1))

if [ -z "${p}" ]; then
   showHelp
fi

if [ -z "${b}" ]; then
   showHelp
fi
1

There are 1 answers

0
paxdiablo On

If you want to ensure you get both options, you can use something like:

no_p=1
no_b=1

while getopts ":p:b:h" o; do
    case "${o}" in
        h)
           showHelp
           ;;
        p)
            p=${OPTARG}
            no_p=0
            ;;
        b)
            b=${OPTARG}
            no_b=0
            ;;
        \? )
            echo "Invalid option: $OPTARG";;
         : )
            echo "Invalid option: ${OPTARG} requires an argument";;
    esac
done

[[ $no_p -eq 1 ]] && echo "No -p provided" && exit 1
[[ $no_b -eq 1 ]] && echo "No -b provided" && exit 1