简体   繁体   中英

Bash Shell Scripting - detect the Enter key

I need to compare my input with Enter / Return key...

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

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

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

Also it is good idea to define empty $IFS (internal field separator) before making comparisons, because otherwise you can end up with " " and "\\n" being equal.

So the code should look like this:

# for distinguishing " ", "\t" from "\n"
IFS=

read -n 1 key
if [ "$key" = "" ]; then
   echo "This was really Enter, not space, tab or something else"
fi

I'm adding below code just for reference if someone will want to use such solution containing countdown loop.

IFS=''
echo -e "Press [ENTER] to start Configuration..."
for (( i=10; i>0; i--)); do

printf "\rStarting in $i seconds..."
read -s -N 1 -t 1 key

if [ "$key" = $'\e' ]; then
        echo -e "\n [ESC] Pressed"
        break
elif [ "$key" == $'\x0a' ] ;then
        echo -e "\n [Enter] Pressed"
        break
fi

done

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

None of these conditions worked for me and so I've came up with this one:

${key} = $'\0A'

Tested on CentOS with Bash 4.2.46.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM