bash - 可以在用户提示时获得 bash 输入吗? (本质上是一个事件监听器)

标签 bash events readline

旧东西:

Background: - Ultimate goal is to put a script in my .bash_profile that warns me by changing text color if I'm typing a commit message and it gets too long (yes I'm aware vim has something like this).

Progress: - I found the read -n option which led me to write this:

while true; do
# This hits at the 53rd character
read -rn53 input
# I have commit aliased to gc so the if is just checking if I'm writing a commit
if [ "${input:0:2}" = "gc" ]; then
    printf "\nMessage getting long"
fi
done

Question: - However, running this takes the user out of the bash prompt. I need a way to do something like this while at a normal prompt. I can't find information on anything like this. Does that mean it's not possible? Or am I just going about it the wrong way?

新进展:

我找到了 bind -x 选项,这让我写下了这个:

check_commit() {
    if [ "${READLINE_LINE:0:13}" == 'git commit -m' ] && [ ${#READLINE_LINE} -gt 87 ]; then
        echo "Commit is $((${#READLINE_LINE} - 87)) characters too long!"
    fi
    READLINE_LINE="$READLINE_LINE$1"
    READLINE_POINT=$(($READLINE_POINT+1))
}
bind -x '"\"": check_commit "\""'

它监听双引号,如果我正在写一个长提交消息,它会告诉我有多少字符超出了限制。还将我输入的字符放入当前行,因为它被绑定(bind)吃掉了。

新问题:

现在我只需要一种方法来放入正则表达式、字符列表或至少一个变量而不是 \" 这样我就可以监听更多的键(是的,我知道 bind -x 可能不打算以这种方式使用。我可以自己检查性能/占用空间/稳定性)。我试过 "$char", "${char }""$(char)" 和其他一些东西,但似乎都不起作用。这里正确的方法是什么?

最佳答案

AFAIK,如果您希望在正常提示期间发生这种情况(当评估 PROMPT_COMMANDPS1 时),则不可能以理智的方式进行。这将涉及为每个 insert-self 等绑定(bind)自定义编译的 readline 函数。

如果您希望在使用内置 prompt 的脚本中发生这种情况,这可以通过

循环粗略地实现
read -e -i $(munge_buf $buf) -n $(buf_warn_len $buf) -p $(buf_warning $buf) buf

类似命令。这将允许您创建 munge_buf() 以根据需要更改当前键入的文本,buf_warn_len() 以计算新的 len 以发出警告(如果warning was already displayed), and buf_warn_msg() 根据缓冲区导出警告消息。

关于bash - 可以在用户提示时获得 bash 输入吗? (本质上是一个事件监听器),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37034584/

相关文章:

events - 分布式调用刷新 umbraco 7 中的缓存后引发事件

table 上的Javascript事件处理程序?

c++ - 从 txt 文件中读取用户名和密码

javascript - 无法在 JavaScript 中同时捕获按键和按键事件

c - 如何在使用 GNU readline 从 stdin 读取时将消息输出到另一个线程上的 stdout 而不会弄乱输入?

c# - readline 然后将指针移回?

bash - 如果模式不存在则删除行

linux - 如何在 bash 中使用 grep 测试进程是否正在运行?

linux - shell如何使用行尾的值重复文本中的行

bash - Facebook 分析为空