Bash Shell Scripting - return key/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

Answers


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

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

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

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

Need Your Help

JQuery Fancybox not working

jquery html css fancybox-2

I've followed the directions, but Fancybox isn't working right. I think I need some extra eyes to tell me what I am doing wrong.

How does one write code that best utilizes the CPU cache to improve performance?

caching performance cpu-cache

This could sound like a subjective question, but what I am looking for are specific instances, which you could have encountered related to this.