2

I am trying to read a single char from stdin inside a shell script (not a bash-script).

I have a script with the following line:

#!/bin/sh

…

char=$(/bin/bash -c 'read -s -n1 key; echo "$key"')

…

This works (assuming bash is installed), but it feels kinda wrong to have that line of code.

Is there a better more portable way to do it?


It should work cross-platform, but even with the few platforms I tested it on (debian, maemo, cygwin, fedora), I could not find a way to do it without having bash installed and invoking an instance of bash just to read one keystroke.

I also tried char="$(dd bs=1 count=1)" but dd only returns/exits after a newline/EOF.


Duplicate

This question has answers that work for my problem.

This might not be an exact duplicate because:

  1. That question is only about ksh.
  2. The top voted answer is only repeating my problem: "How to do it with bash"

But it was asked and answered, because the excepted and the best answer, both work cross platform. The answer I named "best" does it better ;)

Cœur
  • 37,241
  • 25
  • 195
  • 267
Sam
  • 117
  • 12
  • 1
    Isn't `read` builtin part of POSIX shell as well? All options may not work though – anubhava Dec 22 '18 at 07:24
  • 1
    @anubhava Exactly: The `-n` option "returns after reading nchars" is neither POSIX nor is it supported by `dash` or `ash` (sometimes some non-POSIX still works cross platform, sadly not in this case) – Sam Dec 22 '18 at 07:32
  • https://stackoverflow.com/questions/8725925/how-to-read-just-a-single-character-in-shell-script – Diego Torres Milano Dec 22 '18 at 08:27
  • @DiegoTorresMilano Thanks. Just tested [it](https://stackoverflow.com/a/30022297/10822366) with dash and ash. IMHO my question can be closed as a duplicate. Gonna add a comment "it also works with dash/ash" to the answer as soon as I am allowed to do so. – Sam Dec 22 '18 at 09:06

0 Answers0