Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I rerun the second-to-last command?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$ 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?

>Solution :

From the HISTORY EXPANSION section of man bash:

!-n    Refer to the current command minus n

So to run the command before last, you can use !-2

In fact, !! is just a synonym of !-1

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading