bash - automatically capture output of last execut

2019-01-03 11:55发布

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

20条回答
贪生不怕死
2楼-- · 2019-01-03 12:45

By saying "I'd like to be able to use the result of the last executed command in a subsequent command", I assume - you mean the result of any command, not just find.

If thats the case - xargs is what you are looking for.

find . -name foo.txt -print0 | xargs -0 -I{} mv {} /some/new/location/{}

OR if you are interested to see the output first:

find . -name foo.txt -print0

!! | xargs -0 -I{} mv {} /some/new/location/{}

This command deals with multiple files and works like a charm even if the path and/or filename contains space(s).

Notice the mv {} /some/new/location/{} part of the command. This command is build and executed for each line printed by earlier command. Here the line printed by earlier command is replaced in place of {}.

Excerpt from man page of xargs:

xargs - build and execute command lines from standard input

For more detail see man page: man xargs

查看更多
啃猪蹄的小仙女
3楼-- · 2019-01-03 12:46

Here's one way to do it after you've executed your command and decided that you want to store the result in a variable:

$ find . -name foo.txt
./home/user/some/directory/foo.txt
$ OUTPUT=`!!`
$ echo $OUTPUT
./home/user/some/directory/foo.txt
$ mv $OUTPUT somewhere/else/

Or if you know ahead of time that you'll want the result in a variable, you can use backticks:

$ OUTPUT=`find . -name foo.txt`
$ echo $OUTPUT
./home/user/some/directory/foo.txt
查看更多
登录 后发表回答