I wonder if it is possible to make chain actions in Ubuntu terminal like:
action 1 on objectA . then action 2 on objectA
without having to repeat the name of objectA anymore.
Example:
touch file.js && openEditor "$1"
or something like that.
With bash History Expansion, you can refer to the nth word of the current command line using
!#:n
e.g.There is a handy shortcut for a common use case. In your example you are doing:
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 isfile.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 shelldash
goes, you can use$_
to recall last argument of the last command.csh and tcsh have history references, specifically for the last word of the command, you can use
!$
, and for individual arguments -!:<index>
: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:I would recommend against the history approach given in steeldriver's answer. This relies on global state, which is always brittle.
Better is to upfront loop over all needed commands, using a proper variabe:
What's a bit of a problem in general is that Bash doesn't abort when there's a failure, i.e. this actually behaves like
touch foo.txt; gedit foo.txt
instead of chaining with&&
. So, to be safe you can add abreak
:When cooking up a one-liner, I sometimes assign my repeated thing to a shell variable which I use multiple times in the command. I can recall and edit it to use a different arg with up-arrow, control+a, control+right-arrow to get the cursor close to the
t=
.Note that this makes it easy to tack on an extension, or a variation on the name.
Also note that I need a
;
after the variable assignment, becausevar=value cmd
just sets that as an environment variable for that command, and doesn't affect the shell context.