gpt4 book ai didi

bash - 修改 bash 脚本中的 $READLINE_LINE 和 $READLINE_POINT 值

转载 作者:行者123 更新时间:2023-11-29 09:11:07 27 4
gpt4 key购买 nike

回答this question时我使用了一个非常困惑的 bind 函数来根据我的 automplete.sh 脚本的结果修改当前行。

当我最终将此脚本用于个人用途时,我尝试简化 bind 并尝试直接在脚本内进行所有读取和修改。

到目前为止,我可以访问 $READLINE_LINE$READLINE_POINT 并提取我需要的信息,但我无法替换当前值。引用 bind 手册页,这应该可以工作:

When shell-command is executed, the shell sets the READLINE_LINE variable to the contents of the readline line buffer and the READLINE_POINT variable to the current location of the insertion point. If the executed command changes the value of READLINE_LINE or READLINE_POINT, those new values will be reflected in the editing state

我用 bind -x '"\t":autocomplete.sh' 绑定(bind)了我的 scipt,并做了类似这样的事情:

#!/bin/bash
#autocomplete.sh
BASE="${READLINE_LINE% *} "
LAST_CMD="${READLINE_LINE##* }"
EXPANSION=($(magical_autocomplete $LAST_CMD))
#we store the desired value for the line in ${EXPANSION[0]}
[[ ${#EXPANSION[@]} -gt 1 ]] && echo ${EXPANSION[@]:1} #we echo the match if there are more than 1

#Doesn't work, even with simple values like READLINE_LINE="test" or READLINE_POINT=0
READLINE_LINE=${EXPANSION[0]}
READLINE_POINT=${#READLINE_LINE}
#echo READLINE_LINE READLINE_POINT echoes the correct value here

脚本执行后,会显示正确的匹配项,但不会更新当前换行符。当我回显一些信息时,我不能只在 bind 部分重定向脚本的输出。为什么我可以读取变量但不能写入变量?

最佳答案

出于同样的原因,这将不起作用:

$ export a=1
$ bash -c 'echo $a; let a++'
1
$ echo $a
1

环境变量可遗传,不可共享。由于 autocomplete.sh 作为一个新的子进程执行,它可以读取所有父进程的变量,但不能推回新值。

要修改 READLINE_LINEREADLINE_POINT,您必须在同一进程中执行自动完成 - source 和函数会帮助您。

# autocomplete.sh
# should be sourced from ~/.bashrc or something

autocomplete() {
echo $READLINE_LINE $READLINE_POINT
EXPANSION=($(magical_autocomplete $READLINE_LINE))
#we store the desired value for the line in ${EXPANSION[0]}
[[ ${#EXPANSION[@]} -gt 1 ]] && echo ${EXPANSION[@]:1}

READLINE_LINE=${EXPANSION[0]}
READLINE_POINT=${#READLINE_LINE}
}

绑定(bind):

if [[ -s "$HOME/.bashrc.d/autocomplete.sh" ]]; then
source "$HOME/.bashrc.d/autocomplete.sh"
bind -x '"\t" : autocomplete'
fi

关于bash - 修改 bash 脚本中的 $READLINE_LINE 和 $READLINE_POINT 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25178632/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com