Rerun Bash Commands with History Expansions

Cameron Nokes
InstructorCameron Nokes
Share this video with your friends

Social Share Links

Send Tweet

History expansions let you interact with bash's history. For example, if you forgot to run a command with sudo, you can sudo !! to rerun the last command with it. !$ can be used to access the last argument of the last command.

Instructor: [00:00] History expansions always begin with an exclamation mark. For example, to run the last command that we ran again, we can use double exclamation marks. I run the date commands.

[00:11] Then if I just do two exclamation marks and hit enter, you'll see it'll run it again. This is particularly useful if you're doing something that requires superuser permission but forgot to put sudo at the beginning of the command.

[00:24] For example, you can use Bash to turn your wireless on and off, use ifconfig, pass the name of the wireless interface, and say, "Down." Doing this requires that you use sudo. If I do sudo two exclamation marks, you can see it runs it again. Now it works.

[00:42] Another handy history expansion is exclamation mark and dollar sign, which refers to the last argument of the previous commands. For example, if I create a script and I want to give it execute permissions now, I can just do that. I gave that script file execute permissions. It's pretty handy. It saves some typing.