Skip to content

Instantly share code, notes, and snippets.

@embano1
Created June 14, 2017 21:46
Show Gist options
  • Save embano1/8c0aeeb3b1e952ccd4197c677f55c510 to your computer and use it in GitHub Desktop.
Save embano1/8c0aeeb3b1e952ccd4197c677f55c510 to your computer and use it in GitHub Desktop.
zsh History Expansion
man zshexpn
# echo hellow world
^hellow^hello
> echo hello world
(only works on last command)
# replace first arg string in a history command
!353:1:s^hello^hi
# expand to all args from history command
!353:1*
# quote all args from history command
!353:1*:q (or TAB to see more options after last :)
# correct all args from history command
!365:gs/hellow/hello/
# last arg from history command
!353$
# first arg from history command
!353^
# command name of history command
!353:0
# suspend current command
<write> then ESC-q
<another command + ENTER>
# browse through last arguments
ESC-. (multiple times)
# run last command which contains <string>
!?string
(useful when doing git status, git add, git status loops)
# More (from http://chneukirchen.org/blog/archive/2008/02/10-zsh-tricks-you-may-not-know.html)
1. ESC-. inserts the last argument of the previous history line, repeat to go back in history. (Same in Bash.)
2. ESC-' quotes the whole line. (Useful for su -c or ssh).
3. ESC-q clears the line and inserts it again on the next prompt, allowing you to issue an interim command.
4. <(command) returns the filename (in /dev/fd if supported or as a FIFO) of the pipe given by command for reading. (For example, use diff <(ruby foo.rb) <(ruby-1.9 foo.rb) to compare two program outputs).
5. cd old new substitutes old with new once in the pwd and chdirs there.
6. !$ expands to the previous history line’s last argument, !^ expands to the first argument, !:n to the n-th argument.
7. =foo expands to the full path of foo in the PATH (like which foo).
8. for src in *.c do ... done can be abbreviated to for src (*.c) { ... } (which is actually memorizable). You can even drop the curly braces if you don’t have ; in the command.
9. <42-69> globs numbers between 42 and 69. Drop the number(s) to make it open-valued.  {42..69} expands to the numbers between 42 and 69.
10. *** expands recursively like **, but follows symbolic links.
11. Addition! ESC-RETURN inserts a literal newline, so you can edit longer commands easily.
@embano1
Copy link
Author

embano1 commented Aug 6, 2017

Undo zsh expansion:

Example

~# echo hello world
~# hello world
~# echo !!:1 <TAB>
~# echo hello <CTRL + _>
~# echo !!:1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment