Reputation: 6649
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?
Upvotes: 1
Views: 38
Reputation: 46876
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).
Upvotes: 2
Reputation: 785991
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
Upvotes: 2