How can I easily get the second-to-last (penultimate) word/argument from the previous command in a bash interactive shell? I often run commands in the background, and I would like to get the file that was specified before the &
, e.g.,
% echo foo > /tmp/foo &
% cat !$
% &
In the example above, !$
gives the last word, &
. But I want the second-to-the-last argument, /tmp/foo
Note that it is possible to use word designators with a range like !-1:3
, but this is impractical for a command with a large number of words where it's not quickly obvious how many words there are, e.g.,
% (set -x; date; pwd; git status; git diff; git log | tail -30; date; args=--verbose time make test; date) >& /tmp/log/make.test.20150122-Thu-0834 &
% echo !-1:30
/tmp/log/make.test.20150122-Thu-0834
The example above works, but you have to count and know that the word you want is the 30th word, which is time-consuming and error-prone.
Is there an easy way to get the second-to-last (penultimate) word?
UPDATE:
Note that I'm looking for something to type on the command line (e.g., a history expansion, like the !!
event designator, or the $
word designator), as opposed to using readline key bindings (e.g., the esc key).
(Note that this question refers to the arguments of a previous command in an interactive shell, and not to arguments passed to a shell script from the command-line, as some answers and comments here are referring to.)
$_
gives you the last argument of the last command, but that would mean thefoo
ofecho foo
since it doesn't count non-arguments such as I/O redirection or backgrounding. – Devoice