Bash – Put text in the bash command line buffer

bashreadline

I would like to programmatically put a certain piece of text in the command line buffer of bash, read to be edited and used as a command.

What I am looking forward to is something similar to read -i but for commands.

-i text If readline is being used to read the line, text is placed into the editing buffer before editing begins.

Edit: With programmatically I mean that want to write this in a script, launch the script and have the command buffer prepared or the command history modified (as some questions have suggested).

Best Answer

I found a hacky way of doing this on the fzf examples page. This works with bash 4.3 and perl 5.18:

writecmd () { 
  perl -e 'ioctl STDOUT, 0x5412, $_ for split //, do{ chomp($_ = <>); $_ }' ; 
}

# Example usage
echo 'my test cmd' | writecmd

It prints out the command to stdout, but copies it to the command buffer as well. There is also an example on the linked page if you want to execute the command directly.