EastsideDeveloper EastsideDeveloper - 7 months ago 25
Bash Question

Conditional in shell script

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?

Answer

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