7

I know that user input can be read silently using bash with read -s someVar and I was wondering if there is a /bin/sh equivalent that allows user input without displaying it on the command line?

Note: I am just curious if /bin/sh read supports this feature somehow.

mklement0
  • 382,024
  • 64
  • 607
  • 775
Alex Cohen
  • 5,596
  • 16
  • 54
  • 104

1 Answers1

17

Use the stty command to turn off echoing of typed characters.

get_entry () {
  printf "Choose: "
  stty -echo
  IFS= read -r choice
  stty echo
  printf '\n'
}

get_entry

printf "You chose %s\n" "$choice"
mklement0
  • 382,024
  • 64
  • 607
  • 775
chepner
  • 497,756
  • 71
  • 530
  • 681
  • 1
    This is a pretty great solution and it works in both `/bin/sh` and `/bin/bash` – Alex Cohen Jul 24 '16 at 22:18
  • Why `IFS= `? Will that be reset to the default after the function call? – coolaj86 Aug 15 '22 at 21:24
  • 1
    It ensures no leading or trailing whitespace will be stripped from the input. Along with the `-r` option, it means `choice` will be set to the exact keys entered by the user, with no unintentional splitting or expansion applied to the input. The value of `IFS` is local to the execution of `read`, and does not affect the value of `IFS` in the current shell. – chepner Aug 18 '22 at 19:29