Wie erstelle ich eine Bash-Funktion, die zur aktuellen Eingabeaufforderung zurückkehrt?

Wie erstelle ich eine Bash-Funktion, die zur aktuellen Eingabeaufforderung zurückkehrt?

Ist es möglich, eine Bash-Funktion zu erstellen, die zur aktuellen Zeile zurückkehrt?

Zum Beispiel

#~/.bashrc
do-magic() {
    # do some magic and return the input to current prompt line
    # for example "hello"
}
bind -x '"\C-e":do-magic'

Dann

$ echo <ctrl+e>
# become
$ echo hello

Antwort1

Ab Bash 4.0Sie können dies tun, indem Sie die Variablen READLINE_LINEund READLINE_POINTinnerhalb der Funktion ändern. (Der „Punkt“ ist die aktuelle Cursorposition.) Beispiel:

_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'

Antwort2

Sie können "erwarten" verwenden

hier ein ausführliches Beispiel: https://stackoverflow.com/a/77953253/5521600

verwandte Informationen