Insert sudo via the ^ command

command historysudoterminal

Sorry if this is a yes/no question..
I am reading this unix tutorial and found the following:

Repeating and Modifying the Previous
Command

[..]
If you mistype leavenworth as
leaveworth you can correct it with the
following command: % ^leave^leaven

Unfortunately I don't have a computer to try this on, but I was wondering:

Since some commands require sudo to run, could I then write ^^sudo to "insert" sudo to the previous command?

Best Answer

I think using history completion is a much more universal way to do this

$ sudo !!

Most shells have some shortcut for the previous command. That one works in bash and zsh. There are various ways you can do substitution, but usually these are best left for removing or changing bits, if you want to expand it, just grabbing the whole thing is the simplest way. You can add whatever you like before and after the !! to expand on the previous command.

Edit: The original question was about prepending to the previous command which the above covers nicely. If you want to change something inside it as the commentor below the syntax would go like this:

$ sudo !!:s/search/replace/

...where 'search' is the string to match against and replace...well you get the idea.

Related Question