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?

roaima
  • 107,089
  • 14
  • 139
  • 261
testoflow
  • 117
  • 8

1 Answers1

13

You could use read without -p:

printf "put an option: " >&2
read -r option
printf '%s\n' "$option"
jesse_b
  • 35,934
  • 12
  • 91
  • 140
  • needs to call `printf` or `echo`? I mean, can't this be handled by `read` only? thanks – testoflow May 20 '21 at 20:55
  • 2
    @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](https://unix.stackexchange.com/questions/65803/why-is-printf-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