Thursday, July 16, 2009

Ans in Bash: Using the Output of the Latest Command in Bash

MATLAB shell has a sometimes useful variable called ans which you can use in your current calculations as a variable. My TI-83 had one as well actually, but Bash doesn't have one. :)

So, suppose you want to make use of the latest Bash command output. Using !! will redo the previous command. Using !! inside backticks (` `) or $( ) will give its output, as any other Bash command. (Although the $ notation is preferred, the backtick is more convenient in this particular case.)

So, operating on the last output is as simple as:

command_name `!!`

Note that this redoes the previous action, doesn't actually make use of the latest output.

One example:

$ which firefox
/usr/bin/firefox
#This is usually the symlink, we want to learn where the actual target is.
$ ls -l `!!`

Another one:

$ find -name "*.org"
$ emacs `!!`

Note that the -exec option of find or feeding to xargs might be more suitable in most cases, but this is just for demonstration.

Of course, C-p C-a command_name ` C-e ` is an option, but this seems easier.

Inspired via: http://feedproxy.google.com/~r/Command-line-fu/~3/mvkfpS8SZfw/edit-list-of-files-in-last-command

No comments: