9

I know this question has been already asked & answered, but the solution I found listens for space and enter:

while [ "$key" != '' ]; do
        read -n1 -s -r key
done

Is there a way (in bash) to make a script that will wait only for the space bar?

1
  • what should it do when the users hits some other key? (not if, when.)
    – ilkkachu
    Oct 18, 2020 at 15:41

1 Answer 1

21

I suggest to use only read -d ' ' key.

-d delim: continue until the first character of DELIM is read, rather than newline


See: help read

3
  • 1
    Wow! Thank you. This is what I was looking for. @OskarSkog If you mean if it'll show what you're typing, then yes, this will show the keys you're pressing in the terminal, but you can disable it by adding -s flag, like read -s -d ' ' (you don't need the key variable here, if you only want it to wait for the space key)
    – adazem009
    Oct 17, 2020 at 7:54
  • @adazem009 No, I was asking about buffering not echoing. The man page for bash's read doesn't clearly mention it but it obviously works without waiting for a line feed.
    – Oskar Skog
    Oct 17, 2020 at 9:28
  • 1
    @adazem009 On the negative side of things, read is painfully inefficient: it makes a system call for each character it reads (which is kind of why it can do this trick of reading a space without needing Enter). For more reasons to avoid using read unless you have no other option, please see Stéphane's excellent answer here: unix.stackexchange.com/q/169716/88378
    – PM 2Ring
    Oct 18, 2020 at 14:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .