Bash – Using text from previous commands’ output

bashcommand lineio-redirectionosx

EDIT April, 2015:
If you have this same question I recommend also checking http://xiki.org/


I know this is not how terminals work, but I find myself often wishing there was an easy way of using text (copying it, modifying it, etc) that is already on my terminal window history from some previous command output.

I've imagined it like this:

I'm at my bash shell about to enter a command and I realize I need to type something that is already on the screen a few lines above. I can reach for the mouse and select it, but I hate that. What I really wish at this moment is that my whole terminal became a giant Vim buffer, all of it: the prompts, the commands I've typed, and the output from those commands. Everything. And then I could jump a few lines up, maybe edit a little, and yank some text. Then, return to bash shell mode and paste whatever I yanked into the current command line.

I know there are some options:

  • Naturally, pipe the text I need directly from some command's output to a file, or right to the next command. But for that you have to plan in advance or re-execute the command from your history (supposing the output won't change between invocations).

  • To reach for the mouse and select the text to copy. Lame, annoying, I wish I hadn't to do that, (this isn't the GUI stackexchange site, is it? =)

  • To use my (Mac OS X) Terminal application's "Export text as…" option, and save the terminal text to a file. Then open the file and work with it. Almost, but why go through the step of saving to a file on disk?

So the question is: What do you do in this situation? Is there any trick, tool, shell feature that could be useful in this scenario? Do you just resign yourself to use the mouse or re-type whatever you need to type?

It might be that the problem is that I'm not doing things 'the unix way', but c'mon, this is 2010 and I cannot easily copy some text a few lines away from my cursor?

Best Answer

You could use script (use -f to make sure it flushes every time) and you can have all the output in a file.

Use a terminal multiplexer (screen, tmux etc). For instance, for screen http://web.mit.edu/gnu/doc/html/screen_11.html#

Command: copy Enter copy/scrollback mode. This allows you to copy text from the current window and its history into the paste buffer. In this mode a vi-like full screen editor is active, with controls as outlined below.

Other terminal multiplexers surely have more advanced capabilities.

Related Question