2 Ways to Re-run Last Executed Commands in Linux

One of the greatest features of Bash is the command history, which stores all command a user runs, in a history file within his/her home directory (typically /home/$USER/.bash_history). This allows the user to easily recall, edit and rerun previous commands.


Normally, to get a command you recently run, you can use the Up arrow keys to retrieve a previous command. Pressing it constantly takes you through multiple commands in history, so you can find the one you want. Use the Down arrow to move in the reverse direction.


However, the history file may contain a lot of entries, to re-execute a specific command from the history of commands, you can run the history command.

$ history 


Then get the number(s) of the command(s) you want to re-execute (if, for example you want to restart PHP-FPM and view its status, you need to re-execute the commands 997 and 998) as shown.

$ !997
$ !998


You can also re-execute previously used command (sudo yum update) with '!' character followed by a few of the first characters (for instance sud or sudo) of that particular command as shown.

$ !sud
$ !sudo


Was this answer helpful? 0 Users Found This Useful (0 Votes)