Bash Shell Scripting - detect the Enter key

前端 未结 5 1505
时光取名叫无心
时光取名叫无心 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:35

    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
    

提交回复
热议问题