bashshellhistory

copying last bash command into clipboard


Sometimes I need to save the last typed shell command into the clipboard. I can do something like this:

echo !! | xsel --clipboard

Which works successfully.

But when I try to alias the above command:

alias echoxs='echo !! | xsel --clipboard'

Things do not work as expected. In particular, the clipboard contents become literally !!. Obviously, I am missing something about how bash preprocesses commands and aliases. My hope was that an alias, as is intuitive, would be something like a C macro, and that typing the alias would be equivalent to typing its target.

I've tried other approaches and none seem to work. Using HISTFILE inside a script does not work because either commands are cached by the shell session and not immediately written to the file, or multiple terminals mess with the file such that the last command in the file is not always reliably the last command in the current session.

alias='history 1 | xsel --clipboard'

Almost works, except all fails when attempting to modify (eg, cut or sed) the output of history because it is a built-in command.

Is the a way to get the shell's last command through sane stdout?


Solution

  • I'm not sure to understand what you said about "failing when attempting to modify the output of history", so I hope my solution will suit you. I'm using fc to get the last command:

    fc -ln -1 | xsel --clipboard
    

    Here are the meaning of the options: