Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting previous line in Bash after new command?

Tags:

bash

In a Bash terminal, I often type a command and realize that I needed to sudo that command. I hit the up arrow to get the previous command and then backtrack to the beginning type sudo and enter.

Is there any way to type sudo, then press a key to pull down the previous command after sudo?

Thanks!

like image 315
Nathan Avatar asked Dec 28 '25 16:12

Nathan


2 Answers

Yes: you can use "history expansion", and write !!:

$ foo
bash: foo: command not found
$ sudo !!
sudo foo                             <-- it prints out the expanded command
bash: sudo: command not found        <-- and then runs it
like image 187
ruakh Avatar answered Dec 31 '25 12:12

ruakh


sudo !!

!! denotes the previous command

I strongly recommend to visit CommandlineFu which offers a lot of tips and tricks similar to this answer.

One word of caution: if you have HISTIGNORE set like I do, only those commands not ignored can be invoked again this way.

like image 32
0xC0000022L Avatar answered Dec 31 '25 13:12

0xC0000022L