LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Bash: how to read <enter> key (https://www.linuxquestions.org/questions/programming-9/bash-how-to-read-enter-key-388725/)

linmix 12-02-2005 03:56 PM

Bash: how to read <enter> key
 
I have the following code snippet:
Code:

#!/bin/bash
question ()
{
echo '(y for yes, n for no, any other key to cancel)'
read tmp
if [ $tmp = "y" ]; then
 echo "you typed 'yes'"
elif [ $tmp = "n" ]; then
 clear
elif [ $tmp = "c" ]; then
 kill 0
else question
fi
}
question

If I run this script and instead of typing any 'normal' key press <enter> the I get an error message:
Code:

./test.sh: line 6: [: =: unary operator expected
./test.sh: line 8: [: =: unary operator expected
./test.sh: line 10: [: =: unary operator expected

How can I get the script to react to <enter> the same way as to any key (except of course 'y', 'n' and 'c')?

Andrew Benton 12-02-2005 04:11 PM

Try this
Code:

#!/bin/bash
question ()
{
echo '(y for yes, n for no, any other key to cancel)'
read tmp
case "$tmp" in
        y)
                echo "you typed 'yes'"
                ;;
        n)
                clear
                ;;
        c)
                kill 0
                ;;
        *)
                question
esac
}
question


Berhanie 12-02-2005 04:14 PM

the point is to use quotes (so, "$tmp" instead of $tmp).

linmix 12-02-2005 04:38 PM

Thanks!!
it's the double quoting that does it (both in my snippet and in the 'case sollution suggested by Andrew.


All times are GMT -5. The time now is 03:54 AM.