2

I ran up against this question, and i found it quite interesting.

While researching for that, i found out that a solution had been posted already here on AskUbuntu, plus multiple times on StackOverflow and on Unix & Linux, but all the solutions provided involved the use of xclip or xsel, which are not available in a default Ubuntu installation (i.e. they're not present in a Live DVD, for example).

Question: How to copy the stdout of a command to the clipboard in a default Ubuntu installation?

kos
  • 35,891

1 Answers1

3

Copy stdout to the clipboard without installing additional software

Although it seemed impossible to me at first (and it is a bit of a detour), it is very well possible without additional software. The only thing needed is python, like it is installed from a fresh install.

This solution uses python's ability to copy text to the clipboard, and make it available to other applications, as explained (a.o.) here.

The construction

  • The first step is to create an empty textfile, let's say terminal_log.txt
  • The command(s) that run in the terminal are followed by | tee /path/to/terminal_log.txt, e.g.

    pwd | tee /path/to/terminal_log.txt
    

    The output will be in the terminal, as well as written to terminal_log.txt

  • Meanwhile, a script (see below) runs in the background, detecting changes to the file
  • If the file is changed, the change will be copied to the clipboard

The result of the example above:

pwd | tee /path/to/terminal_log.txt

If I open gedit and press Ctrl+V

/home/jacob/Desktop

How to setup

  1. create an empty (log-) file, terminal_log.txt
  2. Copy the script below into an empty file. In the head section, set the path to terminal_log.txt, save it as read_output.py
  3. Start the script with the command

    python /path/to/read_output.py
    
  4. Run in (another) terminal your command, followed by:

    | tee /path/to/terminal_log.txt

  5. The output of your command is copied to the clipboard

If you use it frequently, you could run it as a startup application.

The script

#!/usr/bin/env python
import pygtk
pygtk.require('2.0')
import gtk
import time

#--- enter the path to the log file below
f = "/path/to/terminal_log.txt"
#---

output1 = open(f).read().strip()

while True:
    time.sleep(1)
    output2 = open(f).read().strip()
    if output1 != output2:
        tx = output2.replace(output1, "")
        clipboard = gtk.clipboard_get()
        clipboard.set_text(tx)
        clipboard.store()
    output1 = output2



Additional information

command | tee /path/to/terminal_log.txt

Will not copy stderr to the clipboard. To copy both stdout and stderr to the clipboard, use:

command > >(tee /path/to/terminal_log.txt) 2> >(tee /path/to/terminal_log.txt >&2)

as explained here

Jacob Vlijm
  • 83,767