Monday, April 29, 2024
36
rated 0 times [  36] [ 0]  / answers: 1 / hits: 4355  / 1 Year ago, tue, november 29, 2022, 2:04:41

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?


More From » command-line

 Answers
1

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


[#885] Thursday, December 1, 2022, 1 Year  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
elecerna

Total Points: 140
Total Questions: 121
Total Answers: 107

Location: Northern Ireland
Member since Sun, Nov 21, 2021
2 Years ago
;