# Command line output into the clipboard

Because I use command-line tools so often, I always have the Terminal running. I don’t, however, always have a Terminal window open, and it’s often nice to be able paste the output of a command into whatever I’m writing without having to open a Terminal window, copy the output, then close it back up. Here’s a simple AppleScript which, when combined with FastScripts, saves a couple of steps.

I call it “Unix Command,” and it’s saved in ~/Library/Scripts so FastScripts can access it regardless of the currently active application.

1:  set db to display dialog "Shell command:" default answer "date"
2:  if button returned of db is "OK" then
3:    set cmd to "source ~/.bashrc; " & text returned of db & "| pbcopy"
4:    do shell script cmd
5:  end if


When run—I have it bound to the ⌃⌥⌘U keystroke combination—it puts up a simple dialog box that asks me for the command (or command pipeline) to execute. It puts the result on the clipboard for me to paste into whatever program I happen to be using.

The key to the program is Line 3. It sources my .bashrc to set the environment—and, in particular, the \$PATH—to what I have in the Terminal (all my settings are done in .bashrc rather than .bash_profile). Then, after the semicolon, it runs the command I typed into the dialog box and pipes the result to the pbcopy command, a Mac-specific tool that takes standard input and puts it on the clipboard (also known as the pasteboard, hence the “pb” prefix).

TextMate users may be quietly smirking about now. One of TextMate’s many great features is the ability to treat lines typed into any document as a command. The two TM commands that inspired this script are Execute Line Inserting Result (⌃R) and Execute Line and Replace With Result (⌃⌥R). I use these commands a lot.

Unfortunately, as much as I would like to, I can’t do all my work in TextMate; this script is a way of getting a bit of that TextMate power into Mail, browser forms, anyplace where the clipboard works.