tags:

views:

291

answers:

2

I need to compare my input with enter key/return key...

read -n1 key
if [ $key == "\n" ]
   echo "@@@"
fi

But this is not working.. What is wrong with this code

+1  A: 

read reads a line from standard input, up to but not including the new line at the end of the line. -n specifies the maximum number of characters, forcing read to return early if you reach that number of characters. It will still end earlier however, when the return key is pressed. In this case, its returning an empty string - everything up to but not including the return key.

You need to compare against the empty string to tell if the user immediately pressed return.

read -n1 KEY
if [[ "$KEY" == "" ]]
then
  echo "@@@";
fi
meagar
+4  A: 

Several issues with the posted code. Inline comments detail what to fix:

#!/bin/bash 
# ^^ Bash, not sh, must be used for read options

read -s -n 1 key  # -s: do not echo input character. -n 1: read only 1 character (separate with space)

# double brackets to test, single equals sign, empty string for just 'enter' in this case...
# if [[ ... ]] is followed by semicolon and 'then' keyword
if [[ $key = "" ]]; then 
    echo 'You pressed enter!'
else
    echo "You pressed '$key'"
fi
Mark Rushakoff