简体   繁体   中英

how to detect enter with bash read?

I have this script

while true
do
 size=`tput lines`
 size1="$(($size-15))"
 output1=$(banner)
 output2=$(getMSG)
 clear
 echo "$output1"
 echo "$output2"
 read -t 0.1 -s -n 1 -p "Message: >> $msg" msg1
 if [[ $msg1 == *"\r"* ]]; then
  msg="enter"
 else
  msg="$msg$msg1"
 fi
 sleep 0.01
done

It works fine but i need to detect if the enter key was pressed. How can i do this?? none of my attempts have worked.

I've also tried checking if it something like \n , \r or ^M in it but to no luck.

You can use read -N .

[STEP 101] $ v=
[STEP 102] $ read -N 1 v
    <-- Press <ENTER>
[STEP 103] $ printf '%q\n' "$v"
$'\n'
[STEP 104] $

According to help read :

-N nchars

return only after reading exactly NCHARS characters, unless EOF is encountered or read times out, ignoring any delimiter

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