I'm using Ubuntu 21.10. If I mess up, I can re-run the last command with !!
. Here's an example:
$ apt update
Reading package lists... Done
E: Could not open lock file /var/lib/apt/lists/lock - open (13: Permission denied)
E: Unable to lock directory /var/lib/apt/lists/
W: Problem unlinking the file /var/cache/apt/pkgcache.bin - RemoveCaches (13: Permission denied)
W: Problem unlinking the file /var/cache/apt/srcpkgcache.bin - RemoveCaches (13: Permission denied)
$ sudo !!
sudo apt update
[sudo] password for [me]:
...
Fetched 336 kB in 2s (206 kB/s)
Reading package lists... Done
Building dependency tree
Reading state information... Done
98 packages can be upgraded. Run 'apt list --upgradable' to see them.
That's fine, but instead of rerunning the previous command, how can I run the one before it? Like this:
$ echo hi
hi
$ echo hello
hello
$ !! <-- I'm trying to get that to run 'echo hi'
hello
Basically, here's what I'm looking for
$ echo hi
hi
$ echo hello
hello
$ ??? <-- What can I put here to get it to run 'echo hi'?
echo hello!
hello!
So, given that !!
runs the last command, how can I run the command before the previous one? In my example, instead of typing !!
, what can I run to execute echo hi
?
!!
were useful in plain oldsh
, where there was no command history and editing. Inbash
, there's no more need to use them as you can freely go to previous/next commands by pressing up/down arrow.echo $(!-2)
, there's also a possibility to embed event designators.diff -u <(!-2) <(!!)
orcomm -23 <(!-2 | sort) <(!! | sort)
. Another common use of history expansion for me is!$
to reuse the last argument of the previous command in a new one, likeaur fetch foo
to make a build directory for an AUR package foo, thencd !$
to change the working directory to it.