How to access the last return value in bash?

Simple scenario: I'm looking for a wsdl file lost in the middle of a project.

$ find -name '*.wsdl'
./some/very/very/long/way/to/some/lost/directory/filename.wsdl

Now that I know where it is, I want to do something with this file, say edit it. Instead of copy/pasting the path behind my command, is it possible to use the path returned by find earlier ? Just like it's possible to access the last argument you've typed with !$ or you last command with !!.
I've read that it was possible with $?, but it only returns me an error: 0: command not found

$ echo $?
0: command not found
2

4 Answers

There is no special bash variable for that.

$? contains the exit code of the last command (0 = success, >0 = error-code)

You can use the output of find with the -exec flag, like this:

 find -name '*.wsdl' -exec emacs {} \;

The {} is replaced with the file name found by find. This would execute the command for every found file. If you want to execute a command with all found files as arguments use a + at teh end like this:

 find -name '*.wsdl' -exec emacs {} +

This would open one emacs instance with all found .wsdl files opened in it.

A more general solution is to store the output in a variable:

result=$(find -name '*.wsdl')
emacs $result

This works with all commands, not just find. Though you might also use xargs:

 find -name '*.wsdl' | xargs emacs {}
2

Here's a quick hack that should do what you want with minimal keystrokes, if you don't mind that the last command is executed twice.

Use backtick, ala:

`!!`

e.g.

$ find . -name HardToFind.txt
some/crazy/path/to/HardToFind.txt
$ vim `!!`

*edit: I see the above linked "possibly duped" question also contains this answer. still relevant directly to this one, so leaving it, but sorry for the dupe.

4

Run the command in the command substitution:

output=$(find -name '*.wsdl')

The output is now stored in the output variable which you can use as many times as you like, with the following command:

echo "$output"
7

`!!` is a great solution, but if you want to be even quicker you could use aliases.

Unfortunately it won't work:

~$ alias test='echo `!!`'
~$ test
zsh: command not found: !!

So instead use `fc -e -` Example aliases I use:

copy output:

alias co='echo `fc -e -` | xclip -in -selection clipboard'

open with vim; if output has many lines, opens all of them in tabs:

alias vo='vim -p `fc -e -`'
0

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like