Is there a standard (POSIX) way of asking the user some data from within a shell script, with read
for example, while allowing live edition of the text being typed (what readline does)?
I know bash
has read -e varname
that allows for the person launching the script to use keyboard arrows for exemple, to edit or correct what has just been typed without deleting the last entered characters with backspace.
However, read -e
is bash specific. And still, it is pretty cumbersome to delete all that has been wrote if you realise you made a mistake at the beginning of your long sentence…
Best Answer
The terminal driver does have line editing capabilities on most systems. You'll notice that you can use Backspace, Ctrl-U, sometimes Ctrl-W.
readline
is a GNU library maintained alongsidebash
. There's nothing POSIX about it. POSIX defines an optional line editor (withvi
key binding) forsh
, but no provision to use it outside ofsh
.The
ksh93
shell uses thatvi
-style line editor (also supportsemacs
orgmacs
-style) for itsread
builtin when both stdin and stderr are a terminal and the corresponding option has been set:set -o emacs; IFS= read -r var
for instance forread
to use an emacs-style line-editor.POSIX does specify the
vi
editor though (optional), so you could invokevi
to edit the content of a temporary file.The
zsh
equivalent ofbash
'sread -e
isvared
(a lot more advanced as it's usingzsh
's zle (zsh line editor)).In other shells, you can use some wrappers around readline or other line-editing libraries (like
rlwrap
), or you can invokebash -c 'read -e...'
orzsh -c 'vared...'
.What you could also do is give the opportunity to the user to launch an editor.
Like:
Then the user can press Ctrl-D twice to launch an editor on what he has already entered.
Otherwise, I once wrote that function that should work on most terminals on most Unices that implements a simple line editor.
To be used as:
Or:
if you want a maximum length and/or different filling character and/or an initial value.