現在のプロンプトに戻る bash 関数を作成するにはどうすればよいですか?

現在のプロンプトに戻る bash 関数を作成するにはどうすればよいですか?

現在の行に戻る 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

「expect」を使うことができます

ここに詳細な例があります: https://stackoverflow.com/a/77953253/5521600

関連情報