我试图在Bash命令行上从用户那里得到一些输入。我想在提示中包括一些ANSI转义符(为它加下划线)和一些初始文本,例如:
read -e -i "Lucy and Ricky" -p $'\e[4mWhom do you love?\e[m ' response
这很好。但是,当初始文本超过一定长度时,行编辑会变得混乱,例如:
read -e -i "Lucy and Ricky and Ethel and Fred" -p $'\e[4mWhom do you love?\e[m ' response
当用户按Ctrl-a尝试移动到初始文本的开头时,光标将在其开头的右边(在第一个“ and”的“ d”上)结束几个字符。然后按Ctrl-e,将光标移动到初始文本末尾的右侧几个字符(在本例中为七个字符)。
此外,如果用户在移过初始文本的末尾后尝试编辑其末尾,例如通过删除“和Fred”,则响应变量的内容最终将被额外的字符数截断(同样,在这种情况下为七个)。仅当用户通过先按Ctrl-a将光标移动到行的开头时,才会发生这种情况。似乎试图通过按Ctrl-a移至初始文本的开头,这会弄乱readline对光标位置的跟踪。
以下是一个脚本,可以让您测试此行为:
echo -e "\nCase 1: No ANSI escapes in prompt, short initial text"
read -e -i "Lucy and Ricky" -p 'Whom do you love? ' response
echo $response
echo -e "\nCase 2: With ANSI escapes in prompt, short initial text"
read -e -i "Lucy and Ricky" -p $'\e[4mWhom do you love?\e[m ' response
echo $response
echo -e "\nCase 3: No ANSI escapes in prompt, longer initial text"
read -e -i "Lucy and Ricky and Ethel and Fred" -p 'Whom do you love? ' response
echo $response
echo -e "\nCase 4: With ANSI escapes in prompt, longer initial text"
read -e -i "Lucy and Ricky and Ethel and Fred" -p $'\e[4mWhom do you love?\e[m ' response
echo $response
在每种情况下,编辑初始文本时,请尝试先按Ctrl-a,然后再按Ctrl-e。您会看到一切都按预期进行,直到最后一种情况为止。
输出:
Case 1: No ANSI escapes in prompt, short initial text
Whom do you love? Lucy and Ricky - Works
Lucy and Ricky - Works
Case 2: With ANSI escapes in prompt, short initial text
Whom do you love? Lucy and Ricky - Works
Lucy and Ricky - Works
Case 3: No ANSI escapes in prompt, longer initial text
Whom do you love? Lucy and Ricardo and Ethel and Fred - Works
Lucy and Ricky and Ethel and Fred - Works
Case 4: With ANSI escapes in prompt, longer initial text
Whom do you love? Lucy and Ricky and Ethel and Fred - No worky
Lucy and Ricky and Ethel and Fred- No worky
有什么想法可能会发生这种情况吗?修正或解决方法?
我正在使用4.4.23(1)-发行版(x86_64-apple-darwin18.0.0)的GNU bash。
答案 0 :(得分:1)
ANSI escCode是不可见的,但无论如何都存在,因此会添加到可见字符数中,以将光标移至同一行。
作为一种解决方法,我建议您添加换行符以阅读提示...