How do I execute multiple commands using the same argument?
With bash History Expansion, you can refer to the nth word of the current command line using !#:n
e.g.
$ touch foobar && ls -l !#:1
touch foobar && ls -l foobar
-rw-rw---- 1 steeldriver steeldriver 0 Jun 20 14:54 foobar
$ touch foo bar && ls -l !#:2
touch foo bar && ls -l bar
-rw-rw-r-- 1 steeldriver steeldriver 12 Jun 20 14:58 bar
There is a handy shortcut for a common use case. In your example you are doing:
$ touch file.js
$ openEditor <alt>+<.>
In the second command, the trick is to write openEditor
(with a space after it) followed by Alt+.. This will insert the last argument of the last command, which is file.js
. (If it doesn't work with Alt for some reason, Esc should work as well.)
Since often the "object" is indeed the last argument of the previous command, this can be used frequently. It is easy to remember and will quickly integrate into your set of intuitively used shell shortcuts.
There is a whole bunch of things you can do with this, here's an in-depth article about the possibilities: https://stackoverflow.com/questions/4009412/how-to-use-arguments-from-previous-command.
As a bonus this will work not only in bash but in all programs that use libreadline for processing command line input.
As far as default interactive shell bash
and scripting shell dash
goes, you can use $_
to recall last argument of the last command.
$ echo "Hello World"; echo same "$_"
Hello World
same Hello World
csh and tcsh have history references, specifically for the last word of the command, you can use !$
, and for individual arguments - !:<index>
:
~% echo foo bar
foo bar
~% echo !$
echo bar
bar
% echo bar baz
bar baz
% echo !:1
echo bar
bar
In general, it's just better to assign whatever is objectA
to a variable, and use it in multiple commands, loops, etc. Alternatively, a function could be a choice:
$ foo(){ echo "$@"; stat --print="%F\n" "$@";}
$ foo testdir
testdir
directory