[Bash Tricks]: sudo to last run command

To re-run the previous command, we can use the below special way in bash.

!! #This re-runs the previous command

But the question is, why should i run ‘!!’ instead of using up arrow for previous command. One quick use case would be for running ‘sudo’.

We often end up in ‘Permission denied’ error and re-run the same command using ‘sudo’ either by re-typing the whole command or by giving up arrow and navigate to the beginning using ‘Home’ Button or ‘Side Arrows’ or using ‘Ctrl + a’ (as mentioned in Quick Linux CLI tips, at least it was the best way).

Another best way to re-run the previous command with ‘sudo’ can be the following.

sudo !!

Re run the previous command with sudo

  • Re run the previous command with sudo

Here is the working video of  sudo to last run command

https://youtu.be/_hiv3ef7bg4

[Bash Tricks]: Editing wrongly typed command

 

We often used to type a lengthy command and realize the error after running the command. To correct this error, either we used to re-type the whole command or edit (after up arrow). This can be easily handled with bash tricks by using ‘^’.

Example:

cp /some/very/long/path/for/the/source /some/extra/loong/path/for/destination

Note the wrong spell ‘loong’ in destination path. To resolve this, either we used to re-type the whole command or edit the spell for correct destination.

The above can be done in one liner bash tricks as below.

^loong^long

Here is the working video of  Editing wrongly typed command

https://youtu.be/HEZJ1t_XfKA

[Bash Tricks]: Re-run a range of ‘history’ commands

Sometime we may want to run a range of commands which was run in the past (captured in ‘history‘ command). This can be achieved using ‘fc’ command.

Run ‘history’ command to find the range you want to re-run. For example, range from 1000 to 1010.

fc 1000 1010

The above command will copy the range of commands to a temporary file (same can be saved as shell script if you wish to re-run in future) and open it. The default editor is ‘vim’, use ‘:w [filename]’ to save to new file.

Running a single command from history can be done using ![command number in history]. For example ,

!1000 #This will run the command in 1000th line in history. !1000:p #Just previewing without running

Note: ‘fc’ is bash built-in command. So no external package is needed.

Caution: The above command will be executed once you run ‘fc’. So beware of ‘rm’ and similar commands. Try out in /tmp