如何在交互式shell脚本中编辑“echo”ed行?

时间:2011-08-30 13:39:13

标签: bash shell

我有以下问题:在交互式脚本中,当要求输入时,我想显示一个建议并使其可编辑。它与命令提示符中的“向上箭头和编辑最后一个命令”类似,除非没有“向上箭头”。到目前为止,我尝试了几种不同的东西但没有成功

这些是我尝试的东西:

1)从编辑器获取输入,如下:

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)使用read -e

echo "$SUGGESTION\c"
read -e INPUT # doesn't work as advertised

经过广泛的谷歌搜索后,我确信2)应该有效,但事实并非如此。首先,我不能先删除$ SUGGESTION而不先输入一些输入;在键入一些字符后,退格键会删除整行,而不只是一个字符。

所以我的问题是:如何使“read -e”工作或是否有另一种解决方法?非常感谢您的帮助!

1 个答案:

答案 0 :(得分:4)

它确实像宣传的那样工作,但你需要一个额外的参数来做你想做的事情:

read -e -i "$SUGGESTION" INPUT

不幸的是,这只适用于Bash 4。

如果你有一个C编译器和readline可用,这里有一个你可以使用的快速黑客。将以下内容保存到myread.c(或其他)并进行编译(您需要与readline链接)。对于GCC,那将是: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;
}

你可以像这样使用它:

myread "$SUGGESTION" 2> some_temp_file
if [ $? -eq 0 ] ; then 
  # some_temp_file contains the edited value
fi

有很多改进空间,但我想这是一个开始。