How can I make my script respond to a key press without hitting Enter?

0
0
Asked By User42X On

I'm working on a bash script and want it to respond immediately when the user presses 'x' without needing to hit Enter afterward. Currently, my approach looks something like this:

```bash
cat <<EOF
Press x
EOF

read response

if [[ $response == 'x' ]]; then
printf "you did it!"
else
printf "dummy"
fi
```

The issue is that it requires the user to press x and then Enter. Is there a way to get it to listen for the key press and respond right away?

2 Answers

Answered By CodeNinja23 On

To read just a single character without requiring Enter, you can use `read -rn1 response`. This will let your script respond right after the user presses 'x'.

User42X -

Awesome, thanks!

Answered By ScriptingWizard88 On

Using a HEREDOC for a single line seems a bit overkill, you might want to simplify. But if it makes your actual script clearer, that's fine! Just keep in mind that simpler is often better unless you have a specific need for that complexity.

User42X -

This was just an example, in the real script it's a little longer. Is there a technical disadvantage to using a HEREDOC?

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.