Bash Shell Scripting - detect the Enter key

前端 未结 5 1502
时光取名叫无心
时光取名叫无心 2020-12-14 02:21

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

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

But this

5条回答
  •  半阙折子戏
    2020-12-14 02:57

    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
    

提交回复
热议问题