1
OS: ubuntu 14.04

I have the following script:

#!/bin/bash
read -rsp $'Press Y/y to execute script or any other key to exit...\n' -n1 key
if [ "$key" != 'y' ] || [ "$key" != 'Y' ] ; then
    echo 'You did not press the y key'
    exit
fi
echo 'some other stuff'

No matter what key I press, it always echoes "You did not press the y key"

What am I doing wrong?

2 Answers 2

2

You need && instead of || as logic should say:

if key is not 'y' AND if key is not 'Y' then: error

Code:

if [ "$key" != 'y' ] && [ "$key" != 'Y' ] ; then
    echo 'You did not press the y key'
    exit
fi

If you're using bash then you can shorten that to:

if [[ $key != [yY] ]]; then
    echo 'You did not press the y key'
    exit
fi
Sign up to request clarification or add additional context in comments.

2 Comments

Duh, yes. Too early in the morning. Is the [[]] necessary for the shortened code, or can I use only one set of brackets?
@EastsideDeveloper You need [[...]] to use a pattern as the RHS of !=.
2

What anubhava said. Also, case might be a good alternative to your if statement:

#!/usr/bin/env bash

read -rsp $'Press Y/y to execute script or any other key to exit...\n' -n1 key

case "$key" in
  Y|y)
    echo 'You DID press the y key. Proceeding.'
    ;;
  *)
    printf "I can't handle the '%s' key!\n" "$key"
    exit 1
    ;;
esac

echo 'some other stuff'

Incidentally, except for the read options, this is POSIX-compatible, so it's more portable than bash-only code (like anything using [[ ... ]] conditions).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.