3

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!

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

great! now please run apt-get install foo and apt-get install sudo. :)
@Kaz: I ran this on a Windows box, which has no need for sudo, and certainly no need for foo. I considered SSHing into a handy Linux box and running a command that actually requires root access, like touch /etc/shadow or something, but then I decided this way was more fun. :-)
2
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.