How to make "echo"ed line editable in an interactive shell script?
I have the following problem: in an interactive script, when asking for input, I want to display a suggestion and make it editable. It is a similar functionality to "arrow up and edit the last command" in a command prompt, except without the "arrow up". I tried several different things but no success so far.
These are the things I tried:
1) Get input from editor, like so:
echo "$SUGGESTION\c"
INPUT=`ed -` # problem with this approach is that 'ed' starts in command mode
# by default, and I would need input mode
2) Use read -e
echo "$SUGGESTION\c"
read -e INPUT # doesn't work as advertised
After extensive Googling I am convinced that the 2) should work, but it doesn't. First of all, I cannot delete the $SUGGESTION without typing some input first; after some characters are typed, backspace deletes the whole line, not just one character.
So my question is: how to make "read -e" work or is there another approach to s开发者_开发百科olve this? Your help is very much appreciated!
It does work as advertised, but you need an extra parameter to do what you want:
read -e -i "$SUGGESTION" INPUT
Unfortunately, that's only available in Bash 4.
If you have a C compiler and readline
available, here's a quick hack that you could use. Save the following to myread.c
(or whatever) and compile it (you'll need to link with readline
). For GCC, that would be: gcc -o myread myread.c -lreadline
.
#include <stdio.h>
#include <readline/readline.h>
int main(int argc, char **argv)
{
if (argc != 2)
return 1;
// stuff the input buffer with the default value
char *def = argv[1];
while (*def) {
rl_stuff_char(*def);
def++;
}
// let the user edit
char *input = readline(0);
if (!input)
return 1;
// write out the result to standard error
fprintf(stderr, "%s", input);
return 0;
}
You can use it like this:
myread "$SUGGESTION" 2> some_temp_file
if [ $? -eq 0 ] ; then
# some_temp_file contains the edited value
fi
Lots of room for improvement, but I guess it's a start.
精彩评论