Bash – Processing a Yes/No Response from Bash User

bash

This very well may be stupidity on my part. I would like to accept Yes/No, True/False responses within my Bash script:

test.sh

#!/bin/bash

ARGUMENT=$1

echo User passed in $ARGUMENT

OPTARG=${ARGUMENT:0:1}

if [[ "$OPTARG" -eq 0 ]] || [[ "${OPTARG^^}" == "N" ]]; then
    echo Decline
elif [[ "$OPTARG" -eq 1 ]] || [[ "${OPTARG^^}" == "Y" ]]; then
    echo Accept
else
    echo Invalid argument
fi

Here are some sample results:

./test.sh 0

User passed in 0
Decline

./test.sh 1

User passed in 1
Accept

./test.sh 2

User passed in 2
Invalid argument

./test.sh No

User passed in No
Decline

Now the stumper. Why is [[ "${OPTARG^^}" == "N" ]] returning true for any string!?

./test.sh Yes

User passed in Yes
Decline

./test.sh ThisShouldNotMatch

User passed in ThisShouldNotMatch
Decline

Best Answer

This:

if [[ "$OPTARG" -eq 0 ]] 

Will match any string, unless it is just digits. Use:

if [[ "$OPTARG" == "0" ]] 

Instead.

Related Question