Skip to content

Instantly share code, notes, and snippets.

@ssledz
Last active January 24, 2024 17:05
Show Gist options
  • Save ssledz/6ce47d1af95b5a851c19e1dd6cc5117e to your computer and use it in GitHub Desktop.
Save ssledz/6ce47d1af95b5a851c19e1dd6cc5117e to your computer and use it in GitHub Desktop.
= Resources =
* zsh - http://www.zsh.org/
* ZSH-LOVERS - http://grml.org/zsh/zsh-lovers.html
* manual - http://zsh.sourceforge.net/Doc/Release/index.html
* oh-my-zsh - https://github.com/robbyrussell/oh-my-zsh
* prezo - https://github.com/sorin-ionescu/prezto
* zsh-users - https://github.com/zsh-users
= Functions =
% print -l $fpath # the path of the function
= Expansion =
You can always have a look at all supported types of expansions by typing man zshexpn on your console
== Parameter expansion ==
% foo=Hello
% echo "${foo}, world!"
> Hello, world!
== Command substitution ==
% print $(which zsh)
> /usr/local/bin/zsh
more portable
% print `which zsh`
> /usr/local/bin/zsh
== Arithmetic expansion ==
% echo $(( 5 + 4 ))
> 9
% echo $(( (5 + 4) * 3 ))
> 27
% num=5+4
% echo $(( num * 3 ))
> 27
== Brace expansion ==
% echo picture.jp{eg,g}
> picture.jpeg picture.jpg
% touch log_00{1,2,3}.txt
% ls
> log_001.txt log_002.txt log_003.txt
% touch log_{007..011}.nfo
% ls | grep .nfo
> log_007.nfo log_008.nfo log_009.nfo log_010.nfo log_011.nfo
# ^ - array expansion operator (man zshoptions - the RC_EXPAND_PARAM section and man zshexpn)
% foo=(A B C)
% bar=(1 2 3)
% echo ${^foo}-${^bar}
> A-1 A-2 A-3 B-1 B-2 B-3 C-1 C-2 C-3
= history =
! - default character to trigger history expansion
setopt NO_HIST_VERIFY
setopt HIST_VERIFY # force zsh into asking for confirmation every time you bang a command
Word designators
^: The first argument.
$: The last argument.
%: The most recent match for a given word.
x-y: A range of words. Negative indexes like -i mean 0-i; thus, -1 would mean "the penultimate entry".
*: All the arguments. Return null for events with just one word.
== history expansion ==
% ls *.txt
> readme.txt notes.txt
% !!
% ls *.txt
> readme.txt notes.txt
% sh myscript.sh
> myscript.sh: Error: you need to be root to execute this.
% sudo !!
> myscript.sh: executing myscript.sh
% touch log1.txt log2.txt
% vim !^
% vim log1.txt
% touch log1.txt log2.txt
% vim !$
% vim log2.txt
% history | grep ls
> 6596 ls log_008.nfo
> 6597 ls log_007.nfo log_008.nfo
% more !6597$
% more log_008.nfo
== history substitution ==
% ls
> dir1 file.txt
% mv fiel.txt dir1/
mv: rename fiel.txt to dir1/fiel.txt: No such file or directory
% ^fiel^file
% mv file.txt dir1/
= zle =
% bindkey -e # switch to emacs modes
% bindkey -v # switch to vi mode
% bindkey -N newmap # this creates a keybind named 'newmap'
% bindkey -N mycoolmap emacs # this creates a new keymap based off the existing 'emacs'
% bindkey -A mycoolmap mymacs # this creates an alias 'mymacs' for 'mycoolmap'
% bindkey -l # currently available keymaps
% bindkey -lL # format the output as a series of the bindkey commands
% bindkey -L # a list of all your current bindings, including those of a built-in keymap, formatted in a way you can use within your scripts
% read -k # usefull to figure out the actual escape sequence. For backspace:
> ^?%
== vi mode ==
<Esc> - vi mode
<Esc> + : - run execute prompt, <Ctrl> + g to exit
% hello
execute: ca # <Tab> key for autocomplete or <Ctrl> + g to exit
% Hello
There is a possibility to check whether or not command is bind to a key sequence by putting where-is in execute and
then write a commnad after where-is prompt
% hello
execute: where-is
Where is: capitalize-word_
capitalize-word is not bound to any key
== zle widgets ==
zshzle(1) manpage's STANDARD WIDGETS section
Special variables :
CURSOR : current position of the cursor on the command line.
BUFFER : current editing buffer and can span multiple lines.
LBUFFER/RBUFFER : contents to the left and right of the current cursor, respectively. They too can span multiple lines.
PREBUFFER : buffer already read when editing a continuation line.
WIDGET : name of the widget currently in use by the editor.
Loading tetris widget :)
autoload -Uz tetris
zle -N tetris
bindkey '\et' tetris # <Esc> + t
=== zle widget example ===
function rationalize-dot {
if [[ $LBUFFER = *.. ]]; then
LBUFFER+=/..
else
LBUFFER+=.
fi
}
zle -N rationalize-dot
bindkey . rationalize-dot
= globbing =
setopt NULL_GLOB # discard any pattern without a proper match
setopt NO_NULL_GLOB
setopt NOMATCH
setopt NO_NOMATCH # any pattern that does not match is passed as a literal argument to the command (like in Bash)
setopt CSH_NULL_GLOB # mimics the legacy behavior of csh
setopt NO_CSH_NULL_GLOB
% echo *.zip
zsh: no matches found: *.zip
% setopt NULL_GLOB
% echo *.zip
>
% setopt NO_NOMATCH
% echo *.zip
> *.zip
% echo .*zsh*
> .zsh_aliases .zsh_funcs .zsh_history .zsh_prompt .zshenv .zshrc
% echo *.??
> script.sh
% ls
> Log.log Main.rb README.md script.sh
% echo [ML]* # any filename that starts with either an uppercase letter M or L
> Log.log Main.rb
% echo *.log_[1-9]
> out.log_1 out.log_2 out.log_3
% echo [1-5M]* # any filename starting with any number from one to five or an uppercase M
> Main.rb
% ls
> bindings.c bindings.h bindings.o main.c main.o
% echo *.[^o] # negates character set
> bindings.c bindings.h main.c
== char classes ==
ascii - Anything from the ASCII character set (see man ascii)
lower - Lowercase character
upper - Uppercase character
alpha - Letter
digit - Number
alnum - Alphanumeric character
print - Any printable character
blank - Space or tab character
space - Space character (tab, carriage return, newline and co.)
punct - Anything but an alnum nor a space
echo [[:alpha:]]*
> awesome
% echo [[:digit:]d]* # all the files that start with either a digit character or the lowercase d letter
> 1.txt deploy
== extending globbing ==
setopt EXTENDED_GLOB # enable extending globbing
setopt NO_EXTENDED_GLOB
=== recursive searching ===
**/ - recursive search
***/ - follow symbolic links
% echo **/*.md # perform a recursive search
README.md brew/README.md git/README.md scripts/README.md zsh/README.md
% echo */**/*.md # without current directory
brew/README.md git/README.md scripts/README.md zsh/README.md
=== alternate patterns ===
% echo [[:upper:]]*.(md|txt)
> README.md README.txt
=== numeric ranges ===
<-> - number special pattern
setopt NUMERIC_GLOB_SORT # output a sorted numeric match of any pattern matches
setopt NO_NUMERIC_GLOB_SORT
% ls
> log.txt log_002.txt log_010.txt log_031.txt log_001.txt log_009.txt log_030.txt
% echo log_<->.txt
> log_001.txt log_002.txt log_009.txt log_010.txt log_030.txt log_031.txt
% echo log_<10->.txt # grater then 10
> log_010.txt log_030.txt log_031.txt
% echo log_<10-20>.txt # numbers between 10 and 20
> log_010.txt
=== caret operator ===
pattern^other_pattern - match pattern and avoid match other_pattern
% ls
> README.md README.txt bindings.c bindings.h bindings.o main.c main.o
% echo b^*.o
> bindings.c bindings.h
=== tilde operator ===
% ls
> README.md README.txt bindings.c bindings.h bindings.o main.c main.o
% echo b*~*.o # match b* and avoid matching *.o
> bindings.c bindings.h
% ls tmp
> delete_me.sh out.txt
% echo **/*.sh~tmp/* # match **/*.sh and avoid matching tmp/*
> src/script.sh
=== glob qualifiers ===
(/) - matching directories
(.) - matching files
% echo *zsh
> xx.zsh zsh
% echo *zsh(/)
> zsh
% echo *zsh(.)
> xx.zsh
common qualifiers:
(N) : Remove argument if no matches are found, silently ignore errors. Acts as a per-command NO_GLOB option.
(@) : Symlink qualifier. Used for only selecting symbolic links.
(-@) : A special variation of the previous one. Use this to find any broken symlinks.
(/) : Directories only.
(.) : Files only. Whatever is not either a link, directory, or any of the previous will be selected by this.
(*) : Executable files. Directories need not apply. Think of this as (.) for those files with +x permissions.
(r) : File is readable by the current shell user.
(w) : File is writable by the current shell user.
(x) : File is executable by the current shell user.
(U) : File is owned by the current shell user.
(R) : File is readable by anyone.
(W) : File is writable by anyone.
(X) : File is executable by anyone.
(u:root:) : File is owned by the user root. You can replace the : character with any another pair of symbols such as curly braces: (u{root}). Just refrain from using pipes (|).
(on) : Sort filenames by name. The echo *(on) construct will be analogous to ls.
(On) : Reverse-sort filenames by name.
(oL) : Sort filenames by file size.
(OL) : Reverse-sort filenames by file size.
(om) : Sort filenames by modification date.
(Om) : Reverse-sort filenames by modification date.
% echo *(*r^w) # print regular files that are readable and executable but not writable by your user
% echo *(@,/) # print either symlinks or directories
==== timestamp qualifiers ====
m - modification
a - access
c - creation
m - minute
h - hour
[empty] - day
w - week
M - month
- : (now - x, now) x units of time before now
+ : (inf, now - x) more than x units time from now
% echo *(mh-1) # print files modified in the last hour
% echo *(m-1) # print files modified in the last day
% echo *(ah-1) # print files accessed in the last hour
% echo *(ch-1) # print files created in the last hour
% echo *(mw+3) # print files modified more than three weeks from today
% echo *(m-5mh+2) # print files modified between five days and two hours (now - 5d, now - 2h)
==== file size qualifiers ====
(Lm+size) : The file size is larger than size megabytes.
(Lm-size) : The file is smaller than size megabytes.
(Lk+size) : The file size is larger than size kilobytes.
(Lk-size) : The file is smaller than size kilobytes.
% echo *(Lm+5) # larger than five megabytes.
% echo *(Lm-2) # smaller than two megabytes.
% echo *(Lk+5000) # larger than 5000 kilobytes.
% echo *(Lm-2000) # smaller than 2000 kilobytes.
=== zmv function ===
autoload zmv
-f : Force overwriting of destination files
-i : Interactive prompt for each operation
-n : No execution, just print what happens
-v : Verbose—print a line as it is executed
-w : Implicitly add parenthesis to wildcards in the pattern
-W : Like -w, but turn wildcards in replacement patterns into references
= misc =
#returns n th “word” of that output
echo "year =" ${$(date)[4]}
@petermcmaster9
Copy link

This is great!! Thank you so much.

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