Linux Bash – Create Function to Return to Current Prompt

bashlinux

Is it possible to create a bash function that return to the current line?

For example

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

Then

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

Best Answer

As of Bash 4.0 you can do this by changing the READLINE_LINE and READLINE_POINT variables inside the function. (The 'point' is the current cursor position.) For example:

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