shell script respond to keypress

I have a shell script that essentially says something like

while true; do
    read -r input
    if ["$input" = "a"]; then 
        echo "hello world"           
    fi
done

That is all well, and good, but I just realized having to hit ENTER presents a serious problem in this situation. What I need is for the script to respond when a key is pressed, without having to hit enter.

Is there a way to achieve this functionality within a shell script?


read -rsn1

期待只有一封信(并且不要等待提交)并保持沉默(不要将该信写回)。


所以最后的工作片段如下:

#!/bin/bash

while true; do
read -rsn1 input
if [ "$input" = "a" ]; then
    echo "hello world"
fi
done

Another way of doing it, in a non blocking way(not sure if its what you want). You can use stty to set the min read time to 0.(bit dangerous if stty sane is not used after)

stty -icanon time 0 min 0

Then just run your loop like normal. No need for -r.

while true; do
    read input

    if ["$input" = "a"]; then 
        echo "hello world"           
    fi
done

IMPORTANT! After you have finished with non blocking you must remember to set stty back to normal using

stty sane

If you dont you will not be able to see anything on the terminal and it will appear to hang.

You will probably want to inlcude a trap for ctrl-C as if the script is quit before you revert stty back to normal you will not be able to see anything you type and it will appear the terminal has frozen.

trap control_c SIGINT

control_c()
{
    stty sane
}

PS Also you may want to put a sleep statement in your script so you dont use up all your CPU as this will just continuously run as fast as it can.

sleep 0.1

PSS It appears that the hanging issue was only when i had used -echo as i used to so is probably not needed. Im going to leave it in the answer though as it is still good to reset stty to its default to avoid future problems. You can use -echo if you dont want what you have typed to appear on screen.

链接地址: http://www.djcxy.com/p/25544.html

上一篇: 在Linux shell脚本中处理输入确认

下一篇: shell脚本响应按键