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?

adazem009
  • 621
  • 1
  • 6
  • 10

1 Answers1

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

Cyrus
  • 12,309
  • 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 '20 at 07: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 '20 at 09: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: https://unix.stackexchange.com/q/169716/88378 – PM 2Ring Oct 18 '20 at 14:39