是否可以创建一个返回到当前行的 bash 函数?
例如
#~/.bashrc
do-magic() {
# do some magic and return the input to current prompt line
# for example "hello"
}
bind -x '"\C-e":do-magic'
然后
$ echo <ctrl+e>
# become
$ echo hello
答案1
从 Bash 4.0 开始您可以通过更改函数内的READLINE_LINE
和READLINE_POINT
变量来实现这一点。(“point”是当前光标位置。)例如:
_paste() {
local str="Hello $(date +%F)!"
local len=${#str}
# Note: Bash 5.x wants the length in characters, but Bash 4.x apparently
# wanted bytes. To properly insert non-ASCII text, you used to need:
# local len=$(printf '%s' "$str" | wc -c)
# Insert the text in between [0..cursor] and [cursor..end]
READLINE_LINE=${READLINE_LINE:0:$READLINE_POINT}${str}${READLINE_LINE:$READLINE_POINT}
# Advance the cursor
READLINE_POINT=$((READLINE_POINT + len))
}
bind -x '"\C-e": _paste'
答案2
您可以使用“期望”
这里有一个详细的例子: https://stackoverflow.com/a/77953253/5521600