# Bash History Expansion

`!!` reruns the last command, `!$` grabs its last argument, and `^old^new` fixes a typo without retyping. bash keeps everything you type in `~/.bash_history` — these are the fast ways to pull it back out.

## !! and !$ — rerunning the last command and its last argument

`!!` — reruns the last command. everyone knows the sudo trick:

```bash
apt update
# nope, permission denied
sudo !!
```

`!$` — last argument from whatever you just ran. I use this ALL the time:

```bash
mkdir /tmp/whatever
cd !$
```

saves so much retyping. there's also `!^` for the first arg and `!*` for all of them but honestly I mostly just use `!$`.

## !cmd — rerunning by prefix, with :p to preview it first

`!ssh` runs your last command that started with `ssh`. kinda dangerous though — you might not remember exactly what that command was. safer version: slap `:p` on the end to preview it:

```bash
!ssh:p
# shows what it WOULD run, without actually running it
```

`Ctrl+R` is honestly better for searching history though, see [Bash Keyboard Shortcuts](/articles/bash-keyboard-shortcuts).

## ^old^new — fixing a typo without retyping

this one's underrated:

```bash
cat /etc/ngnix/nginx.conf
^ngnix^nginx
```

boom, fixed. only does the first occurrence though.

---

see also: [Bash Keyboard Shortcuts](/articles/bash-keyboard-shortcuts), [Bash Brace Expansion](/articles/bash-brace-expansion)

[the bash man page on this stuff](https://man7.org/linux/man-pages/man1/bash.1.html#HISTORY_EXPANSION) if you want the deep dive
