Ubuntu – How to assign a certain keyboard shortcut to paste specific item

clipboardcustomizationshortcut-keys

I regularly need to paste a certain bit of text or a file (probably an image), but it becomes rather long and annoying to keep going back and putting it into my clipboard as I have to copy and paste other things too.

So what would be very useful for me would be to have a certain keyboard shortcut which just pastes a certain piece of text or a file, but is separate from the main clipboard. The keyboard shortcut should either put the item into my main clipboard when pressed or it should just paste it itself, whichever is easier to do (if both as as easy as each other then both would be nice as there are occasions when I will need one, and occasions when I will need the other).

Is there a way of doing something like this? I am running Ubuntu GNOME 16.04 with GNOME 3.20.

Best Answer

The command to get a fixed string into the clipboard is very easy, it's simply

xsel -ib <<< 'Your string goes here'

or if you want to read the string from a file

xsel -ib < your-file.txt

or from a command output

your-command | xsel -ib

Directly writing a fixed string by emulating keypresses is not much more complex though

xvkbd -file - <<< 'Your string goes here'

or if you want to read the string from a file

xvkbd -file your-file.txt

or from a command output

your-command | xvkbd -file -

You can simply create a custom shortcut in the System SettingsKeyboardShortcuts configuration and assign a command to the key combination you wish.

But take care that the shortcut interpreter is not Bash or a similar shell, so our <<< ("here string" syntax) or | pipes will not work. To solve this anyway, we simply enclose our shell command with bash -c "INSERT COMMAND HERE". Just pay attention that you don't use double quotes inside the command then.

Here are the commands how you would have to enter them into the shortcut settings:

  • Copy "my string" to clipboard:

    bash -c "xsel -ib <<< 'my string'"
    
  • Copy content of my-file.txt to clipboard:

    bash -c "xsel -ib < my-file.txt"
    
  • Copy output of my-command to clipboard:

    bash -c "my-command | xsel -ib"
    
  • Directly paste/write "my string":

    bash -c "xvkbd -file - <<< 'my string'"
    
  • Directly paste/write content of my-file.txt:

    bash -c "xvkbd -file my-file.txt"
    
  • Directly paste/write output of my-command:

    bash -c "my-command | xvkbd -file -"
    

Please note that neither xselnor xvkbd are installed by default, so you probably need to install them first using this command:

sudo apt-get install xsel xvkbd