Shell event designators — the `!` syntax available in bash, csh, tcsh, and zsh — let you reference and reuse previous commands and their arguments without retyping them. The post explains the three-part pattern `![event][:word][:modifier]`, covering event designators like `!!`, `!ssh`, `!-2`, word designators like `!:$`, `!:*`, `!:1-2`, and modifiers like `:h` (dirname), `:t` (basename), `:r` (strip extension), and substitution with `:s/foo/bar/`. It also covers the POSIX `fc` command for editing previous commands in your editor of choice, including bulk replacement across multiple history entries. Four practical shortcuts worth memorizing are highlighted: `!$`, `!:0`, `!$:h`, and `!$:t`.

9m read timeFrom refp.se
Post cover image
Table of contents
Don't yell at your colleagues; yell in your shell #Don't Repeat Yourself. #What is this magic an event designator? #POSIX and the power of fc #Yell responsibly #Frequently Asked Questions #Further Reading #

Questions this post answers

How do I rerun the last command with sudo in bash?

Use `sudo !!` — the `!!` event designator expands to the entire previous command. So if you ran `apt install awesome-package` and got a permissions error, typing `sudo !!` reruns it as `sudo apt install awesome-package` without retyping anything. Developers who live in the terminal pick up tricks like these on daily.dev.

How do I cd to the directory of the last argument I typed in bash?

Use `cd !$:h` — `!$` refers to the last argument of the previous command, and the `:h` modifier strips the filename to give just the directory path (equivalent to `dirname`). For example, after `touch ~/projects/work/awesome.sh`, running `cd !$:h` expands to `cd ~/projects/work`. Shell productivity patterns like this surface regularly for developers who follow command-line topics on daily.dev.

How do I edit a previous shell command in my text editor instead of on the command line?

Use the POSIX `fc` command. Running `fc` opens the previous command in your editor (controlled by `$FCEDIT` or `$EDITOR`, falling back to `ed`). You can also run `fc -3 -1` to edit the last three commands in one buffer, or `fc -e 'sed -i s/prod-01/test-01/g' -3 -1` to apply a substitution across multiple history entries and rerun them. Not available in minimal shells like dash or busybox ash. Keeping up with shell tooling like fc is easier when terminal-focused posts reach you through daily.dev.

103 Impressions