Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatically capture output of last command into a variable using Bash?

I'd like to be able to use the result of the last executed command in a subsequent command. For example,

$ find . -name foo.txt ./home/user/some/directory/foo.txt 

Now let's say I want to be able to open the file in an editor, or delete it, or do something else with it, e.g.

mv <some-variable-that-contains-the-result> /some/new/location 

How can I do it? Maybe using some bash variable?

Update:

To clarify, I don't want to assign things manually. What I'm after is something like built-in bash variables, e.g.

ls /tmp cd $_ 

$_ holds the last argument of the previous command. I want something similar, but with the output of the last command.

Final update:

Seth's answer has worked quite well. Couple of things to bear in mind:

  • don't forget to touch /tmp/x when trying the solution for the very first time
  • the result will only be stored if last command's exit code was successful
like image 891
armandino Avatar asked May 10 '11 19:05

armandino


People also ask

What in bash lets you take the output of a previous command and use it as input in the next command?

Pipe is used to combine two or more commands, and in this, the output of one command acts as input to another command, and this command's output may act as input to the next command and so on.

How do you repeat the last command in bash?

To get the same effect as using the up arrow once, which is showing the last command run without executing it, you can use CTRL+P. Or change the number, and run any of your last commands. For example changing the 1 to a 2 will run the second from last command. This is all made possible by using bash history.

How do you capture output of a command in a variable in a shell script?

Here are the different ways to store the output of a command in shell script. You can also use these commands on terminal to store command outputs in shell variables. variable_name=$(command) variable_name=$(command [option ...] arg1 arg2 ...) OR variable_name=`command` variable_name=`command [option ...]


1 Answers

I don't know of any variable that does this automatically. To do something aside from just copy-pasting the result, you can re-run whatever you just did, eg

vim $(!!) 

Where !! is history expansion meaning 'the previous command'.

If you expect there to be a single filename with spaces or other characters in it that might prevent proper argument parsing, quote the result (vim "$(!!)"). Leaving it unquoted will allow multiple files to be opened at once as long as they don't include spaces or other shell parsing tokens.

like image 159
Daenyth Avatar answered Sep 25 '22 21:09

Daenyth