是否可以建立一個傳回目前行的 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
(「點」是目前遊標位置。)例如:
_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