4
read -r -p "put an option: " option
echo $option

this works but shellcheck gives me:

In POSIX sh, read -p is undefined.

How to get user input with a prompt into a variable in a posix compliant way?

Chris Davies
  • 116,213
  • 16
  • 160
  • 287
testoflow
  • 117

1 Answers1

14

You could use read without -p:

printf "put an option: " >&2
read -r option
printf '%s\n' "$option"
jesse_b
  • 37,005
  • needs to call printf or echo? I mean, can't this be handled by read only? thanks – testoflow May 20 '21 at 20:55
  • 3
    @testoflow It depends. Are you writing a portable script, meant to run in any POSIX shell, or are you targeting a specific shell? shellcheck gives you that warning when you target sh, but common implementations (e.g. dash, busybox ash) actually support prompting with read -p. It won't work, however, in zsh and, I think, in ksh88 and derivatives (and in the original Bourne shell). – fra-san May 20 '21 at 21:10
  • @testoflow: You could use echo but printf is better than echo. As fra-san mentioned many, if not most systems would accept -p but if you want to be pure POSIX sh you can't use it. If you know it wont be an issue you can ignore certain shellcheck rules. – jesse_b May 20 '21 at 23:52