Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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
share|improve this question
    
what happens if you quote this? OPTARG="${ARGUMENT:0:1}" –  mikeserv Mar 15 at 16:20
1  
Nevermind. Goldilocks is right. –  mikeserv Mar 15 at 16:20

3 Answers 3

up vote 10 down vote accepted

This:

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

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

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

Instead.

share|improve this answer

Although the problem in your code has been well explained by goldilocks, I cannot resist saying that your code is needlessly long. You could simplify it a lot.

The following is equivalent to your desired code:

echo User passed in $1
if [[ "$1" == [nN0]* ]]; then      # First argument starts with either n, N, or 0
    echo Decline
elif [[ "$1" == [yY1]* ]]; then    # First argument starts with either y, Y, or 1
    echo Accept
else
    echo Invalid argument
fi

You might also want to refer to Conditional Constructs in the manual.

share|improve this answer
    
Thank you, devnull. I will definitely use this trick in future scripts! I was torn as to whether I should accept your answer, but I think the distinctions in goldilocks' answer may be helpful for others. –  i_grok Mar 16 at 14:23
    
@i_grok I did mention in my answer that goldilocks' answer points to the problem. I simply presented an alternate approach that seemed more readable. It's good to see multiple approaches to solving a problem come up. Regarding which answer is accepted is a relatively trivial affair. –  devnull Mar 16 at 14:39

Also you can use case

read -p 'Do you want to Continue (yes/no?): ' 
case $REPLY in
       [yY]|[yY][eE][sS]) echo Accept             ;;
           [nN]|[nN][oO]) echo Decline            ;;
                       *) echo "Invalid argument" ;;
esac
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.