Shell Script, read on same line after echoing a message
Solution: read -p "Enter [y/n] : " opt
From help read
:
-p prompt output the string PROMPT without a trailing newline before
attempting to read
The shebang #!/bin/sh
means you're writing code for either the historical Bourne shell (still found on some systems like Solaris I think), or more likely, the standard shell language as defined by POSIX. This means that read -p
and echo -n
are both unreliable.
The standard/portable solution is:
printf 'Enter [y/n] : '
read -r opt
(The -r
prevents the special treatment of \
, since read
normally accepts that as a line-continuation when it's at the end of a line.)
If you know that your script will be run on systems that have Bash, you can change the shebang to #!/bin/bash
(or #!/usr/bin/env bash
) and use all the fancy Bash features. (Many systems have /bin/sh
symlinked to bash
so it works either way, but relying on that is bad practice, and bash
actually disables some of its own features when executed under the name sh
.)