Zsh
One of the most religious choices UNIX/LINUX users do is the choice of shell. Users that are new to UNIX just
accept the default shell, but as time goes and you get more advanced, you many want to change shell because
you realy misses a certain feature.
zsh is a great UNIX shell. It has all the benefits of
other standard shells, and a hell of a lot more on top. I'm interested in the interactive features
in particular, because they can save you a lot of time and effort. Yes! I'm a
One area in which it is dramatically powerful is in its ability to interactively evaluate arguments.
It can do command name completion, filename completion, and is extensible such that it can use programs
to evaluate possible command completions.
It is highly configurable, has a lot of cool features that a lazy man
like me likes. The only problem is that Bash is the standard shell and
that Zsh is not installed everywhere, so I tried to use Bash for a day,
and the missing cyclic completion made me run back to Zsh.
- very close to ksh/sh grammar, with csh additions
- most features of ksh, bash, and tcsh
- can emulate ksh, csh or POSIX sh
- 100 builtins, 145 options, 166 key bindings
- select
- autoloaded functions (loaded from a file when they are first referenced)
- short for loops, ex: for i (*.c) echo $i
- conditional expressions (test builtin, [ ... ], and ksh-style [[ ... ]])
- global aliases (may be expanded anywhere on the line)
- directory stack access with =num
- PATH substitution ("ls -l =zsh" is the same as "ls -l /path/to/zsh" or "ls -l `which zsh`")
- process substitution (vi =(cmd) edits the output of cmd)
- generalized pipes (ls foo 2>>(cmd1) 2>>(cmd2) pipes stdout to cmd1 and stderr to cmd2)
- arithmetic expressions
- advanced globbing:
- ls **/file searches recursively for "file" in subdirectories
- ls file<20-> matches file20, file21, file22, etc.
- ls *.(c|pro) matches *.c and *.pro
- ls *(R) matches only world-readable files
- ls (#a1)README matches README with one error, e.g. RADME, REEDME, RAEDME
- ls (#ia1)README same but case insensitive
- ls *.c~lex.c matches all .c files except lex.c
- See zshexpn(1) /Glob Qualifiers for details
- null command shorthands:
- "< file" is same as "more <file"
- "> file" is same as "cat > file"
- ">> file" is same as "cat >>file"
- ksh-style co-processes
- ability to line edit a multi-line command. I find this very useful. Say you've just typed in a multi-line "for"..."done" line
and need to fix a type or redo it slightly differently. Under zsh you simply using ^p like any single line.
- the "vared" builtin -- allows you to line edit a variable (e.g. "vared path").
- allows you to defined what a "word" is (e.g. for using backward-word). Using the vared command makes it nice and simple, just do "vared WORDCHARS".
- ccepts both csh and sh syntax, which is useful if you're used to a tcsh environment at work, or just like some of the csh things like
"prompt" instead of "PS1", or using a wordlist $path rather than a colon-separated $PATH.
- ability to try out an interactive command with "M-x" without having to specifically bind it
- the "infer next" command. (Bash now has something limilar, operate-and-get-next (C-o). I like zsh's approach where you use this
command when you want the next command; bash requires you to think
- automatic completion on variables names, e.g. type "export DISP" and hit tab. (I just checked, in bash you can use
Esc-$ to specifically complete a variable name in zsh the default compctl (completion) has been setup to complete for a variable name
if the command is "export". While the zsh seemed easier, I guess the bash approach allows you to control it more.) ahead and realize before submitting that you will want the next command.)
- automatic file stream teeing (ls > foo >bar puts output in two places)
- chpwd() function run every time you change directory (useful for updating the status line)
- job control and csh-style history
- full vi line editing, including "c2w" and "y$" and such things
- full emacs line editing
- line editor is programmable via shell functions
- access and manipulate editor state via builtins and parameters
- user-defined `widgets' behave like other editor functions
- keymap customisation
- example functions provided
- incremental history search
- magic-space history
- spelling correction
- array parameters
- $LINENO, $RANDOM, $SECONDS, $cdpath, $COLUMNS, $fignore, $HISTCHARS, $mailpath, $UID, $EUID, $GID, $EGID and $USERNAME can be assigned to
- with autocd option, typing a directory name by itself is the same as typing "cd dirname"
- menu completion: pressing TAB repeatedly cycles through the possible matches
- incremental path hashing
- automatic process time reporting for commands that run over a certain limit
- full tcsh-style prompt substitution
- utmp login/logout reporting
- with histverify option, performing csh-style history expansions causes the input line to be brought up for editing instead of being executed
- with sunkeyboardhack option, accidently typed trailing ` characters are removed from the input line (for those of you with Sun keyboards)
- "cd old new" replaces "old" with "new" in directory string
- autoloaded functions (loaded from a file when they are first referenced)
- "cd old new" replaces "old" with "new" in directory string
- generalized argument completion, including:
- command name completion
- filename and path completion
- hostname completion
- key binding completion
- option completion
- variable name completion
- user-specified keyword completion
- generalized argument completion, new system based on shell functions:
- highly context sensitive
- large (and I mean large) set of completions supplied, from a2ps to zstyle
- partial file path completion
- spelling correction and approximate completion of any completable word
- highly configurable expansion of shell arguments
- completion list colouring [`colorizing' for you lot over there]
- selection of completion elements with the cursor
- full scrolling of lists (in optional module)
- completion of words from the history list
- `styles' feature for versatile configuration
- `tags' feature for choosing completions preferentially
- `match' specifications, allowing e.g.
- variant forms: NO_glob, noglob, _NOGLOB_ all from the keyword glob
- partial-word matches with arbitrary anchors, e.g.
- - z_t.c -> zle_tricky.c
- -c.u.s -> comp.unix.shell
- complete control over case-insensitive matching
- can be defined globally or for individual completions
- bindable special completion functions
- prompt on right side of screen
- command scheduling (like at(1), but in the shell's context)
- tty mode freezing
- up to 9 startup files (but you only need 1 or 2)
- which -a cmd lists all occurences of "cmd" in the path
- dynamically loadable binary modules
- an FTP client which runs in the shell, with function suite
- math functions
- builtin interface to the `stat' system command
- builtin versions of standard commands (mv, ln, etc.) for emergencies
- special parameters to access internal state of hash tables etc.
- special associative array to access contents of files directly
- profiler for shell functions
- a pseudo-terminal handler, for purposes like `expect'
- builtins for interaction with termcap and terminfo
- Login/Logout monitoring
For more informations take a quick look at the manpages:
$ man -k zsh
zsh (1) - the Z shell
zshall (1) - the Z shell meta-man page
zshbuiltins (1) - zsh built-in commands
zshcompctl (1) - zsh programmable completion
zshcompsys (1) - zsh completion system
zshcompwid (1) - zsh completion widgets
zshcontrib (1) - user contributions to zsh
zshexamples (1) - some examples
zshexpn (1) - zsh expansion and substitution
zsh-lovers (1) - tips, tricks and examples for the Z shell
zshmisc (1) - everything and then some
zshmodules (1) - zsh loadable modules
zshoptions (1) - zsh options
zshparam (1) - zsh parameters
zshzftpsys (1) - zftp function front-end
zshzle (1) - zsh command line editor
A complete(?) list of al available
shells
- ash (ftp://sunsite.unc.edu/pub/Linux/apps/tex/ntex/languages/)
- a lightweight Bourne compatible shell. Great for machines with low memory, but does not provide all the extras of shells like bash, tcsh, and zsh
- GNU Bash (http://www.gnu.org/software/bash/)
- GNU Bourne-Again SHell - an sh-compatible command language interpreter that executes commands read from the standard input or from a file. Bash also
incorporates useful features from the Korn and C shells
- BUSH (http://www.pegasoft.ca/bush.html)
- a powerful Linux/UNIX shell for designing secure, reliable shell scripts that can be later compiled as a fast executable programs
- BSH (http://www.schellong.de/)
- Note: Read http://members.pop-hannover.de/~ilse/bsh-programming-harmful.html (local copy)!
- Cash (http://pauillac.inria.fr/cash/)
- the Caml Shell from Bruno Verlyck
- Clam Shell (http://www.cis.rit.edu/~sdlpci/Software/projects/#clam)
- Clam Shell is a simple shell, made to be a testbed for user interface ideas. The name is sort of an acronym for "CSH-Like-Amiga-Modular Shell". It originally was going to be a testbed to see how the Amiga's "Assign" methodology for virtual/physical devices (like dh0:, sys:, files:, etc.) works in a *nix environment. I tried it out under another shell, but the project i was putting my code base into was extremely messy, and I wanted to have full control over the source...
- csh (URL anyone?)
- Note: Read http://www.faqs.org/faqs/unix-faq/shell/csh-whynot/
- DASH (http://gondor.apana.org.au/~herbert/dash/)
- DASH is a POSIX-compliant implementation of /bin/sh that aims to be as small as possible. It does this without sacrificing speed where possible. In fact, it is significantly faster than bash (the GNU Bourne-Again SHell) for most tasks.
- Emacs Shell (http://www.newartisans.com/johnw/eshell.html)
- Eshell is a command shell implemented entirely in Emacs Lisp. It invokes no external processes beyond those requested by the user. It is intended to be a functional replacement for command shells such as bash, zsh, rc, 4dos; since Emacs itself is capable of handling most of the tasks accomplished by such tools.
- flash (http://www.netsoc.ucd.ie/flash/)
- a (hopefully) secure shell which will only execute administrator defined programs, while also being very user friendly. Flash is fully windowed (using
an ncurses interface), is driven by cursor keys, has hotkey support, has fascist logging support and more.
- es (http://hawkwind.utcs.utoronto.ca:8001/mlists/es.html)
- extensible shell from Paul Haahr and Byron Rakitzis
- PDKSH (http://www.kornshell.com/)
- Public Domain Korn Shell, also a complete, powerful, high-level programming language for writing applications, often more easily and quickly than with other high-level languages
- Lash (http://lash.kerneled.com/)
- a shell designed primarily for slow PCs that features modularity and simple built-in aliases. It also implements a history command, and includes colorful prompts and "callbex" (call before exec)
- nadvsh (http://nadvsh.sourceforge.net/)
- The New Adventure Shell is a shell script that will make your Un*x shell act like a text adventure game.
- NR Shell (http://sf.gds.tuwien.ac.at/n/nr/nrsh/
- a small shell for Linux systems that is a mix between command.com and bash
- mud-shell (http://www.xirium.com/tech/mud-shell/)
- TODO
- osh (http://home.no.net/pusleole)
- a lightweight unix shell
- posh (http://packages.debian.org/unstable/shells/posh)
- a stripped-down version of pdksh with several improvements that aims for compliance with Debian's /bin/sh policy, and few extra features
- psh (http://www.focusresearch.com/gregor/sw/psh/)
- Perl Shell - A fairly simple read-eval loop. The -w flag and 'use strict' are not employed so that the user is not bound by their stipulations. Setting $^W = 1 will turn on warnings, and calling '' will do the usual thing if called by the user
- rc (http://www.star.le.ac.uk/~tjg/rc/)
- a command interpreter and programming language similar to sh. The shell offers a C-like syntax (much more so than the C shell), and a powerful mechanism for manipulating variables. It is reasonably small and reasonably fast, especially when compared to contemporary shells
- rss (http://www.cycom.se/dl/rrs)
- Reverse Remote Shell: a reverse (connecting) remote shell. Instead of listening for incoming connections it will connect out to a listener (rrs in listen mode). The listener will accept the connection and receive a shell from the remote host. rrs features full pseudo-tty support, full OpenSSL support (high encryption, client/server authentication, choice of cipher suites), Twofish encryption, a simple XOR cipher, plain-text (unencrypted) session, peer-side session monitoring (snooping), daemon option and reconnection features
- sash (http://www.canb.auug.org.au/~dbell/)
- a stand-alone shell with many built-in commands
- Scsh (http://www.scsh.net/)
- a Unix shell embedded in Scheme. It provides full access to POSIX as well as extensions common to most Unix implementations
- Tcsh (http://www.tcsh.org/)
- C shell with file name completion and command-line editing. tcsh is an enhanced but completely compatible version of the Berkeley UNIX C shell (csh)
- vimsh (http://users.adelphia.net/~bsturk/myprog.html)
- an interactive shell buffer. It allows execution of shell commands in a vim buffer, without having to suspend the vim session
- Woosh (http://wosx30.eco-station.uni-wuerzburg.de/~martin/woosh/)
- an attempt at building an object-oriented shell
- Zoidberg (http://zoidberg.student.utwente.nl/)
- a modular perl shell. The plan is to create a modular oo-oriented perl program with the possibility to overload any function and load perl modules on runtime
- Zsh (http://www.zsh.org/)
- a shell designed for interactive use, although it is also a powerful scripting language. Many of the useful features of bash, ksh, and tcsh were incorporated into zsh; many original features were added
sh csh ksh bash tcsh zsh rc es
Job control N Y Y Y Y Y N N
Aliases N Y Y Y Y Y N N
Shell functions Y(1) N Y Y N Y Y Y
"Sensible" Input/Output redirection Y N Y Y N Y Y Y
Directory stack N Y Y Y Y Y F F
Command history N Y Y Y Y Y L L
Command line editing N N Y Y Y Y L L
Vi Command line editing N N Y Y Y(3) Y L L
Emacs Command line editing N N Y Y Y Y L L
Rebindable Command line editing N N N Y Y Y L L
User name look up N Y Y Y Y Y L L
Login/Logout watching N N N N Y Y F F
Filename completion N Y(1) Y Y Y Y L L
Username completion N Y(2) Y Y Y Y L L
Hostname completion N Y(2) Y Y Y Y L L
History completion N N N Y Y Y L L
Fully programmable Completion N N N N Y Y N N
Mh Mailbox completion N N N N(4) N(6) N(6) N N
Co Processes N N Y N N Y N N
Builtin artithmetic evaluation N Y Y Y Y Y N N
Can follow symbolic links invisibly N N Y Y Y Y N N
Periodic command execution N N N N Y Y N N
Custom Prompt (easily) N N Y Y Y Y Y Y
Sun Keyboard Hack N N N N N Y N N
Spelling Correction N N N N Y Y N N
Process Substitution N N N Y(2) N Y Y Y
Underlying Syntax sh csh sh sh csh sh rc rc
Freely Available N N N(5) Y Y Y Y Y
Checks Mailbox N Y Y Y Y Y F F
Tty Sanity Checking N N N N Y Y N N
Can cope with large argument lists Y N Y Y Y Y Y Y
Has non-interactive startup file N Y Y(7) Y(7) Y Y N N
Has non-login startup file N Y Y(7) Y Y Y N N
Can avoid user startup files N Y N Y N Y Y Y
Can specify startup file N N Y Y N N N N
Low level command redefinition N N N N N N N Y
Has anonymous functions N N N N N N Y Y
List Variables N Y Y N Y Y Y Y
Full signal trap handling Y N Y Y N Y Y Y
File no clobber ability N Y Y Y Y Y N F
Local variables N N Y Y N Y Y Y
Lexically scoped variables N N N N N N N Y
Exceptions N N N N N Y N Y
Key to the table above.
Y Feature can be done using this shell.
N Feature is not present in the shell.
F Feature can only be done by using the shells function
mechanism.
L The readline library must be linked into the shell to enable
this Feature.
Notes to the table above
1. This feature was not in the orginal version, but has since become
almost standard.
2. This feature is fairly new and so is often not found on many
versions of the shell, it is gradually making its way into
standard distribution.
3. The Vi emulation of this shell is thought by many to be
incomplete.
4. This feature is not standard but unoffical patches exist to
perform this.
5. A version called 'pdksh' is freely available, but does not have
the full functionality of the AT&T version.
6. This can be done via the shells programmable completion mechanism.
7. Only by specifing a file via the ENV environment variable.
A collection of tips out of the mailinglists
(zsh-users and zsh-workers),
google, newsgroups or by myself. My favorite ZSH-Geeks are
Andrew 'zefram' Main.
Barton E. Schaefer,
Peter Stephenson,
Stéphane Chazelas,
Sven Guckes,
Thanks for your cool and incredible tips. I learned much from you!
You spotted a typo? An bug/error? Let me know! See http://www.strcat.de/contact.html
for my GnuPG - Key and then send me an email.
# remove leading zeros
$ var=00004402
$ echo ${var##0#}
# or
$ var=00004402
$ echo ${var/(#m)<->/$((MATCH))}
# sorting file's names in ascending order according to the last two numerical fields of the files
# names. And then cat these files into one based on the ascending order depicted here.
$ find . -type f -regex ".*[.][0-9]+[.][0-9]+$" -print0 |sort -Vz | xargs -r0 cat > myfile
# or - with zsh -
$ cat ./*.<->.<->(n)
# random numbers
$ echo $[${RANDOM}%1000] # random between 0-999
$ echo $[${RANDOM}%11+10] # random between 10-20
$ echo ${(l:3::0:)${RANDOM}} # N digits long (3 digits)
# simplify and if then else
$ if [[ "$LOGNAME" != davidr ]] ; then
cd /o/inetpub/wwwdev/www.some.co.uk/epsystem/epadmin
else
cd /c/inetpub/wwwdev/www.some.co.uk/epsystem/epadmin
fi
$ cd ${${${LOGNAME:#davidr}:+/o}:-/c}/inetpub/wwwdev/www.some.co.uk/epsystem/epadmin
or
$ cd /$([[ "$LOGNAME" != davidr ]] && echo o || echo c)/inetpub/wwdev/blabla
# Show newest directory
$ ls -ld *(/om[1])
# reverse a word
$ echo "${(j::)${(@Oa)${(s::):-hello}}}"
# random array element
$ FILES=( .../files/* )
$ foobar feh $FILES[$RANDOM%$#FILES+1]
# cat first line in all files in this dir
$ for file (*(ND-.)) IFS= read -re < $file
# test if a parameter is numeric
$ if [[ $1 == <-> ]] ; then
echo numeric
else
echo non-numeric
fi
# Show me all the .c files for which there doesn't exist a .o file.
$ c=(*.c) o=(*.o(N)) eval 'ls ${${c:#(${~${(j:|:)${o:r}}}).c}:?done}'
# All files in /var/ that are not owned by root
$ ls -ld /var/*(^u:root)
# All files for which the owner hat read and execute permissions
$ echo *(f:u+rx:)
# The same, but also others dont have execute permissions
$ echo *(f:u+rx,o-x:)
# brace expansion - example
$ X=(A B C)
$ Y=(+ -)
$ print -r -- $^X.$^Y
A.+ A.- B.+ B.- C.+ C.-
# Fetch the newest file containing the string 'fgractg*.log' in the filename and contains the string
# 'ORA-' in it
$ file=(fgractg*.log(Nm0om[1]))
$ (($#file)) && grep -l ORA- $file
# without Zsh
$ files=$( find . -name . -o -prune -name 'fgractg*>log' -mtime 0 -print )
> if [ -n "$files" ]; then
> IFS='
> '
> set -f
> file=$(ls -td $files | head -1)
> grep -l ORA- "$file"
> fi
# keep specified number of child processes running until entire task finished
$ zsh -c 'sleep 1 & sleep 3 & sleep 2& print -rl -- $jobtexts'
# Remove zero length and .bak files in a directory
$ rm -i *(.L0) *.bak(.)
# print out files that dont have extensions
$ printf '%s\n' ^?*.*
$ printf '%s\n' ^?*.[^.]*(D)
$ ls -d -- ^?*.*(D)
# Finding files which does not contain a specific string
$ print -rl file* | comm -2 -3 - <(grep -l string file*)'
$ for f (file*(N)) grep -q string $f || print -r $f'
# Show/Check whether a option is set or not. It works both with $options as
# with $builtins
$ echo $options[correct]
off
$ $options[zle]
on
# Count the number of directories on the stack
$ print $((${${(z)${(f)"$(dirs -v)"}[-1]}[1]} + 1)) # or
$ dirs -v | awk '{n=$1}END{print n+1}'
# Matching all files which do not have a dot in filename
$ ls *~*.*(.)
# Show only the ip-address from ``ifconfig device''
$ print ${${$(LC_ALL=C /sbin/ifconfig eth0)[7]}:gs/addr://} # ifconfig from net-tools (Linux)
$ print ${$(/sbin/ifconfig tun0)[6]} # ifconfig from 4.2BSD {Free,Net,Open}BSD
# Ping all the IP addresses in a couple of class C's or all hosts into /etc/hosts
$ for i in {1..254}; do ping -c 1 192.168.13.$i; done
or
$ I=1; while ( [[ $I -le 255 ]] ) ; do ping -1 2 150.150.150.$I; let I++; done
or
$ for i in $(sed 's/#.*//' > /etc/hosts | awk '{print $2}')
: do
: echo "Trying $i ... "
: ping -c 1 $i ;
: echo '============================='
: done
# load all available modules at startup
$ typeset -U m
$ m=()
$ for md ($module_path) m=($m $md/**/*(*e:'REPLY=${REPLY#$md/}'::r))
$ zmodload -i $m
# Rename all files within a directory such that their names get a numeral prefix in the default sort order.
$ i=1; for j in *; do mv $j $i.$j; ((i++)); done
$ i=1; for f in *; do mv $f $(echo $i| awk '{ printf("%03d", $0)}').$f; ((i++)); done
$ integer i=0; for f in *; do mv $f $[i+=1].$f; done
# Find (and print) all symbolic links without a target within the current dirtree.
$ $ file **/*(D@) | fgrep broken
$ for i in **/*(D@); [[ -f $i || -d $i ]] || echo $i
$ echo **/*(@-^./=%p)
$ print -l **/*(-@)
# List all plain files that do not have extensions listed in `fignore'
$ ls **/*~*(${~${(j/|/)fignore}})(.)
# see above, but now omit executables
$ ls **/*~*(${~${(j/|/)fignore}})(.^*)
# Print out files that dont have extensions (require setopt extendedglob dotglob)
$ printf '%s\n' ^?*.*
# List files in reverse order sorted by name
$ print -rl -- *(On)
or
$ print -rl -- *(^on)
# Synonymic to ``ps ax | awk '{print $1}'''
$ print -l /proc/*/cwd(:h:t:s/self//)
# Get the PID of a process (without ``ps'', ``sed'', ``pgrep'', .. (under Linux)
$ pid2 () {
> local i
> for i in /proc/<->/stat
> do
> [[ "$(< $i)" = *\((${(j:|:)~@})\)* ]] && echo $i:h:t
> done
> }
# for X in 'n' 'o' 'p' 'q' 'r' 's' 't' 'u' 'v' 'w' 'x' 'y'; do ...
$ for (( i = 36#n; i <= 36#y; i++ )); do
> print ${$(([##36]i)):l}
> done
# or in combination with ``dc''
$ print {$((##n))..$((##y))}P\ 10P | dc
# or with ``eval''
$ eval print '${$(([##36]'{$((36#n))..$((36#y))}')):l}'
# foreach in one line of shell
$ for f (*) print -r -- $f
# copy a directory recursively without data/files
$ dirs=(**/*(/))
$ cd -- $dest_root
$ mkdir -p -- $dirs
# or without zsh
$ find . -type d -exec env d="$dest_root" sh -c ' exec mkdir -p -- "$d/$1"' '{}' '{}' \;
# If `foo=23'', then print with 10 digit with leading '0'.
$ foo=23
$ print ${(r:10::0:)foo}
# find the name of all the files in their home directory that have more than 20 characters in their file names
print -rl $HOME/${(l:20::?:)~:-}*
# Save arrays
$ print -r -- ${(qq)m} > $nameoffile # save it
$ eval "m=($(cat -- $nameoffile)" # or use
$ m=("${(@Q)${(z)"$(cat -- $nameoffile)"}}") # to restore it
# get a "ls -l" on all the files in the tree that are younger than a specified age (e.g
# "ls -l" all the files in the tree that where modified in the last 2 days)
$ ls -tld **/*(m-2)
# This will give you a listing 1 file perl line (not à la ls -R).
# Think of an easy way to have a "ls -R" style output with
# only files newer than 2 day old.
$ for d (. ./**/*(/)) {
> print -r -- $'\n'${d}:
> cd $d && {
> l=(*(Nm-2))
> (($#l)) && ls -ltd -- $l
> cd ~-
> }
> }
# If you also want directories to be included even if their mtime
# is more than 2 days old:
$ for d (. ./**/*(/)) {
> print -r -- $'\n'${d}:
> cd $d && {
> l=(*(N/,m-2))
> (($#l)) && ls -ltd -- $l
> cd ~-
> }
> }
# And if you want only the directories with mtime < 2 days to be listed:
$ for d (. ./**/*(N/m-2)) {
> print -r -- $'\n'${d}:
> cd $d && {
> l=(*(Nm-2))
> (($#l)) && ls -ltd -- $l
> cd ~-
> }
> }
# print 42 ``-''
$ echo ${(l:42::-:)}
# or use ``$COLUMS''
$ echo ${(l:$COLUMNS::-:)}
# and now with colors (require autoload colors ;colors)
$ echo "$bg[red]$fg[black]${(l:42::-:)}"
# Redirect STDERR to a command like xless without redirecting STDOUT as well.
$ foo 2>>(xless)
# but this executes the command asynchronously. To do it synchronously:
$ { { foo 1>&3 } 2>&1 | xless } 3>&1
# Rename all MP3-Files from name with spaces.mp3 to Name With Spaces.mp3
$ for i in *.mp3; do
> mv $i ${${(C)i}:s/Mp3/mp3/}
> done
# Match file names containing only digits and ending with .xml (requiresetopt kshglob)
$ ls -l [0-9]##.xml
$ ls -l <0->.xml
# Remove all "non txt" files
$ rm ./^*.txt
# Move 200 files from a directory into another
$ mv -- *([1,200]) /another/Dir
# Convert images (foo.gif => foo.png):
$ for i in **/*.gif; convert $i $i:r.png
# convert a collection of mp3 files to wave or cdr (e.g. file.wav -> file.mp3)
$ for i (./*.mp3){mpg321 --w - $i > ${i:r}.wav}
# Download with LaTeX2HTML created Files (for example the ZSH-Guide):
$ for f in http://zsh.sunsite.dk/Guide/zshguide{,{01..08}}.html; do
> lynx -source $f >${f:t}
> done
# Move all files in dir1 and dir2 that have line counts greater than 10 to another directory say "/more10"
$ mv dir[12]/**/*.cr(-.e{'((`wc -l < $REPLY` > 10))'}) /more10
# Make with dpkg a master-list of everyfile that it has installed
$ diff <(find / | sort) <(cat /var/lib/dpkg/info/*.list | sort)
# Replace this fucking Escape-Sequences:
$ autoload colors ; colors
$ print "$bg[cyan]$fg[blue]You are a idiot" >> /dev/pts/3
# Get ASCII value of a character
$ char=N ; print $((#char))
# Filename "Erweiterung"
# Note: The (N) says to use the nullglob option for this particular glob pattern.
$ for i in *.o(N); do
> rm $i
> done
# Rename files; i. e. FOO to foo and bar to BAR
$ for i in *(.); mv $i ${i:l} # `FOO' to `foo'
$ for i in *(.); mv $i ${i:u} # `bar to `BAR'
# Show all suid-files in $PATH
$ ls -latg ${(s.:.)PATH} | grep '^...s'
# or more complex ;)
$ print -l ${^path}/*(Ns,S)
# or show only executables with a user given pattern
$ print -l ${^path}/*vim*(*N)
# gzip files when containing a certain string
$ gzip ${(ps:\0:)"$(grep -lZ foobar ./*.txt(.))"}
# A small one-liner, that reads from stdin and prints to stdout the first unique line
# i. e. does not print lines that have been printed before (this is similar to the unique
# command, but unique can only handle adjacent lines).
$ IFS=$'\n\n'; print -rl -- ${(Oau)${(Oa)$(cat file;echo .)[1,-2]}}
# Lists every executable in PATH
$ print -l ${^path}/*(-*N)
# Match all .c files in all subdirectories, _except_ any SCCS subdirectories?
$ ls **/*.c~(*/)#SCCS/*
# List all `README' - files case-insensitive with max. one typo
$ ls **/*(#ia2)readme
# case insensitive checking for variables
$ if [[ $OSTYPE == (#i)LINUX*(#I) ]]; then
> echo "Penguin on board."
> else
> echo "Not a Linux."
> fi
A list of valid glob Qualifiers can be found in zshexpn(1)
Note: **/ is equivalent to (*/)#! For example:
$ print (*/)#zsh_us.ps
zsh-4.2.3/Doc/zsh_us.ps
$ print **/zsh_us.ps
zsh-4.2.3/Doc/zsh_us.ps
# find all directories, list their contents and output the first item in the above list.
$ print -rl /home/me/**/*(D/e{'reply=($REPLY/*(N[-1]:t))'})
# List all files older than 15mins
$ ls -ldrt -- *(mm+15)
# Just regular files
$ ls -ldrt -- *(.mm+15)
# List the unbroken sysmlinks under a directory.
$ ls -ld /my/path/**/*(D@-^@)
# the age of the pointed to file for symlinks
$ ls -Lldrt -- *(-mm+15)
# Use find(1) to find all directories except the ".svn" ones, then use grep on all *.c/*.h/*.S
# files in each directory.
$ setopt extendedglob
$ grep pattern (^.svn/)#*.[xhS](.) # skips dot files and dot directories
# or - without Zsh
$ find . -type d ! -name .svn | sed 's/./\\&/g;s|.*|grep whatever &/*.[xhS]|' | sh
# Quote from Usenet
# > I need to write a script that searches through a folder on my Linux
# > home server and copies only files where the width is greater than the
# > height, but it also needs to flatten the directory structure and
# > rename files as it copies. So the first picture found may be several
# > directories deep in the source but this should be copied to the root
# > of the SD card and named say 00000001.JPG and the next file found
# > where width > height should be copied and renamed 00000002.JPG.
width_greater_than_height() {
local w h
identify -format '%w %h' ${1-$REPLY} |
read w h && ((w > h))
}
typeset -Z8 i=0
setopt extendedglob
for f (**/*.(#i)jp(e|)g(D.+width_greater_than_height)) {
((i++))
cp -- $f /path/to/dest/$i.JPG
}
# Search for `README' in all Subdirectories
$ ls -l **/README
# find directories that contain both "index.php" and "index.html", or in general, directories
# that contain more than one file matching "index.*"
$ ls **/*(D/e:'[[ -e $REPLY/index.php && -e $REPLY/index.html ]]':)
# or
$ ls **/*(D/e:'l=($REPLY/index.*(N)); (( $#l >= 2 ))':)
# Find command to search for directory name instead of basename
$ print -rl /**/*~^*/path(|/*)
# or - without Zsh
$ find / | grep -e /path/ -e '/path$'
# Print he path of the directories holding the ten biggest C regular files in the current
# directory and subdirectories.
$ print -rl -- **/*.c(D.OL[1,10]:h) | sort -u
# Find files with size == 0 and send a mail
$ files=(**/*(ND.L0m+0m-2))
> (( $#files > 0 )) && print -rl -- $files | mailx -s "empty files" foo@bar.tdl
# recursive chmod
$ chmod 700 **/(.) # Only files
$ chmod 700 **/(/) # Only directories
# print out all of the files in that directory in 2 columns
$ print -rC2 -- ${1:[...]}/*(D:t)
# ^- number ob columns
# or - if you feel concerned about special characters - use
$ list=(${1:[...]}/*(ND:t))
$ (($#list)) && print -rC2 -- ${(V)list}
# Search all files in /home/*/*-mail/ with a setting ``chmod -s'' flag (recursive, include
# dotfiles) remove the setgid/setuid flag and print a message
$ chmod -s /home/*/*-mail(DNs,S) /home/*/*-mail/**/*(DNs,S))
# or with a small script
$ for file (/home/*/*-mail(DNs,S) /home/*/*-mail/**/*(DNs,S)) {
> print -r -- $file
> chmod -s $file && print -r fixed $file
> }
# or use ``zargs'' (require autoload zargs) prevent the arg list too long error
$ zargs /home/*/*-mail(DNs,S) /home/*/*-mail/**/*(DNs,S)) -- chmod -s
# List files beginning at `foo23' upwards (foo23, foo24, foo25, ..)
$ ls -l foo<23->
# get all files that begin with the date strings from June 4 through June 9 of 2004
$ ls -l 200406{04..10}*(N)
# or if they are of the form 200406XX (require ``setopt extended_glob''
$ ls -l 200306<4-10>.*
# remove spaces from filenames
$ for a in ./**/*\ *(Dod); do mv $a ${a:h}/${a:t:gs/ /_}; done
# Show only all *.c and *.h - Files
$ ls -l *.(c|h)
# Show only all *.c - files and ignore `foo.c'
$ ls *.c~foo.c
# show data to *really* binary format
$ zsh -ec 'while {} {printf %.8x $n;repeat 8 \
> {read -ku0 a printf \ %.8d $(([##2]#a))};print;((n+=8))}' < binary
# Show only world-readable files
$ ls -l *(R)
# List files in the current directory are not writable by the owner
$ print -l ~/*(ND.^w)
# find and delete the files which are older than a given parameter (seconds/minutes/hours)
$ rm -f /Dir/**/*(.mh+3) # deletes all regular file in /Dir that are older than 3 hours
$ rm -f /Dir/**/*(@mm+3) # deletes all symlinks in /Dir that are older than 3 minutes
$ rm -f /Dir/**/*(ms+30^/) # deletes all non dirs in /Dir that are older than 30 seconds
$ rm ./**/*(.Dmh+1,.DL0) # deletes all folders, sub-folders and files older than one hour
$ rm -f **/*(mh+6) # deletes all files more than 6 hours old
$ rm ./*(Om[1,-11]) # removes all files but the ten newer ones (delete all but last 10 files in a directory)
Note: If you get a arg list too long, you use the builtin rm. For example:
$ zmodload zsh/files ; rm -f **/*(mh+6)
or use the zargs function:
$ autoload zargs ; zargs **/*(mh+6) -- rm -f
# A User's Guide to the Z-Shell /5.9: Filename Generation and Pattern Matching
# find all files in all subdirectories, searching recursively, which have a given
# name, case insensitive, are at least 50 KB large, no more than a week old and
# owned by the root user, and allowing up to a single error in the spelling of
# the name. In fact, the required expression looks like this:
$ ls **/(#ia1)name(LK+50mw-1u0)
# Change the UID from 102 to 666
$ chown 666 **/*(u102)
# List all files which have not been updated since last 10 hours
$ print -rl -- *(Dmh+10^/)
# delete only the oldest file in a directory
$ rm ./*filename*(Om[1])
# Sort the output from `ls -l' by file size
$ ls -fld *(OL)
# find most recent file in a directory
$ setopt dotglob ; print directory/**/*(om[1])
# Show only empty files which nor `group' or `world writable'
$ ls *(L0f.go-w.)
# find - and list - the ten newest files in directories and subdirs (recursive)
$ print -rl -- **/*(Dom[1,10])
# Print only 5 lines by "ls" command (like ``ls -laS | head -n 5'')
$ ls -fl *(DOL[1,5])
# display the 5-10 last modified files
$ print -rl -- /path/to/dir/**/*(D.om[5,10])
# find all files without a valid owner
$ chmod someuser /**/*(D^u:${(j.:u:.)${(f)"$(</etc/passwd)"}%%:*}:)
# find all the empty directories in a tree
$ for f in ***/*(/l2); do foo=($f/*(N)); [[ -z $foo ]] && print $f; done
# Note:Since Zsh 4.2.1(?) the glob qualifier F indicates a non-empty directory.
Hence *(F) indicates all subdirectories with entries, *(/^F) means all subdirectories with no
entries.
$ ls -ld *(/^F)
# remove empty directories afterwards
$ rmdir ./**/*(/od) 2> /dev/null
# Show only files are owned from group `users'
$ ls -l *(G[users])
Modifiers are a powerful mechanism that let you modify the results returned by
parameter, filename and history expansion. See zshexpn(1)
for details.
# Remove a trailing pathname component, leaving the head. This works like `dirname'.
$ echo =ls(:h)
/bin
# Eliminate the duplicated elements of an array and keep the remain emements order appeared in
# the original array.
$ a=( a a f 1 3 b b 3 5 4 4 )
$ a=("${(u@)a")
# Remove all leading pathname components, leaving the tail. This works like `basename'.
$ echo =ls(:t)
ls
# Remove the suffix from each file (*.sh in this example)
$f:e is $f file extension
:h --> head (dirname)
:t --> tail (basename)
:r --> rest (extension removed)
$ for f (*.sh) mv $f $f:r
# Remove a filename extension of the form `.xxx', leaving the root name.
$ echo $PWD
/usr/src/linux
$ echo $PWD:t
linux
# Remove all but the extension.
$ foo=23.42
$ echo $foo
23.42
$ echo $foo:e
42
# Print the new command but do not execute it. Only works with history expansion.
$ echo =ls(:h)
/bin
$ !echo:p
$ echo =ls(:h)
# Quote the substituted words, escaping further substitutions.
$ bar="23'42"
$ echo $bar
23'42
$ echo $bar:q
23\'42
# Convert the words to all lowercase.
$ bar=FOOBAR
$ echo $bar
FOOBAR
$ echo $bar:l
foobar
# Convert the words to all uppercase.
$ bar=foobar
$ echo $bar
foobar
$ echo $bar:u
FOOBAR
# convert 1st char of a word to uppercase
$ foo="one two three four"
$ print -r -- "${(C)var}"
One Two Three Four
(see zshmisc(1) for more
informations (or less ${^fpath}/zmv(N))
# Append `exit 1' at the end of all *.sh - files
$ echo "exit 1" >> *.sh
# adding files to foobar.tar.gz
$ eval set =(gunzip < foobar.tar.gz) '
tar rf $1 additional.txt &&gzip < $1 > foobar.tar.gz'
# Redirect output to a file AND display on screen
$ foobar >&1 > file1 > file2 > ..
# pipe single output to multiple inputs
$ zcat foobar.Z >> (gzip -9 > file1.gz) \
>> (bzip2 -9 > file1.bz2) \
>> (acb --best > file1.acb)
# Append /etc/services at the end of file `foo' and `bar'
$ cat /etc/services >> foo >> bar
# Pipe STDERR
$ echo An error >&2 2>&1 | sed -e 's/A/I/'
# send standard output of one process to standard input of several processes in the pipeline
$ setopt multios
$ process1 > >(process1) > >(process2)
# initializing a variable and simultaneously keeping terminal output
$ setopt multios
$ { a=$(command >&1 >& 3 3 > &- 2>&1);} 3>&1
# redirect stderr two times
$ setopt multios ; program 2> file2 > file1 2>&1
# Duplicating stdout and stderr to a logfile
$ exec 3>&1 > logfile 2>&2 2>&1 >&3 3>&-
# redirect stderr (only) to a file and to orig. stderr:
$ command 2>&2 2>stderr
# redirect stderr and stdout to separate files and both to orig. stdout:
$ command 2>&1 1>&1 2>stderr 1>stdout
# redirect stderr and stdout to separate files and stdout to orig. stdout AND stderr to orig. stderr:
$ command 2>&2 1>&1 2>stderr 1>stdout
# More fun with STDERR ;)
$ ./my-script.sh 2> >(grep -v moron >error.log) | process-output > output.log
$ echo "Thats STDOUT" >>(sed 's/stdout/another example/' > foobar)
Note: ``-n'' means no execution (just print what would happen)
# rename file contents with its directory name as a prefix
$ zmv '(*)/(*.txt)' '${1}_$2'
# rename a section of a filename, i. e. example.1.{txt,conf,db} or 12345.1.{wav,ogg,mp3} and
# change the 1 to a 2 in the filename while preserving the rest of it.
$ zmv -n '(*.)(<->)(.[^.]#)' '$1$(($2+1))$3' # would rename x.0001.y to x.2.y.
$ zmv -n '(*.0#)(<->)(.[^.]#)' '$1$(($2+1))$3'
# Rename files to lower case
$ zmv '*' '${(L)f}'
# serially all files (foo.foo > 1.foo, fnord.foo > 2.foo, ..)
$ autoload zmv
$ ls *
1.c asd.foo bla.foo fnord.foo foo.fnord foo.foo
$ c=1 zmv '*.foo' '$((c++)).foo'
$ ls *
1.c 1.foo 2.foo 3.foo 4.foo foo.fnord
# Rename "file.with.many.dots.txt" by substituting dots (exept for the last
# one!) with a space
$ touch {1..20}-file.with.many.dots.txt
$ zmv '(*.*)(.*)' '${1//./ }$2'
# Remove the first 4 chars from a filename
$ zmv -n '*' '$f[5,-1]' # NOTE: The "5" is NOT a mistake in writing!
# Rename names of all files under the current Dir to lower case, but keep Dir names as-is.
$ zmv -Qv '(**/)(*)(.D)' '$1${(L)2}'
# replace all 4th character, which is "1", with "2" and so on
$ autoload -U zmv
$ zmv '(???)1(???[1-4].txt)' '${1}2${2}'
# Remove the first 15 characters from a string
$ touch 111111111111111{a-z}
$ autoload zmv
$ zmv '*' '$f[16,-1]'
# Replace spaces (any number of them) with a single dash in file names
$ autload zmv
$ zmv -n '(**/)(* *)' '$1${2//( #-## #| ##)/-}'
# or - with Bash
$ find . -depth -name '* *' -exec bash -c '
> shopt -s extglob
> file=$1
> dir=${file%/*}
> name=${file##*/}
> newname=${name//*([ -]) *([ -])/-}
> mv -i -- "$file" "$Dir/$newname"' {} {} \;
# Clean up file names and remove special characters
$ autoload zmv
$ zmv -n '(**/)(*)' '$1${2//[^A-Za-z0-9._]/_}'
# Add *.py to a bunch of python scripts in a directory (some of them end in *.py and give them
# all a proper extension
$ autoload zmv
$ zmv -n '(**/)(con*)(#qe,file $REPLY | grep "python script",)' '$1$2.py'
# lowercase all extensions (i. e. *.JPG) incl. subfolders
$ autoload zmv
$ zmv '(**/)(*).(#i)jpg' '$1$2.jpg'
# Or - without Zsh
$ find Dir -name '*.[jJ][pP][gG]' -print | while read f
> do
> case $f in
> *.jpg) ;
> *) mv "$f" "${f%.*}.jpg" ;
> esac
> done
# remove leading zeros from file extension
$ autoload zmv
$ ls
filename.001 filename.003 filename.005 filename.007 filename.009
filename.002 filename.004 filename.006 filename.008 filename.010
$ zmv '(filename.)0##(?*)' '$1$2'
$ ls
filename.1 filename.10 filename.2 filename.3 filename.4 filename.5 filename.6 ...
# renumber files.
$ autoload zmv
$ ls *
foo_10.jpg foo_2.jpg foo_3.jpg foo_4.jpg foo_5.jpg foo_6.jpg foo_7.jpg foo_8.jpg foo_9.jpg
$ zmv -fQ 'foo_(<0->).jpg(.nOn)' 'foo_$(($1 + 1)).jpg'
$ ls *
foo_10.jpg foo_11.jpg foo_3.jpg foo_4.jpg foo_5.jpg foo_6.jpg foo_7.jpg foo_8.jpg foo_9.jpg
# adding leading zeros to a filename (1.jpg -> 001.jpg, ..
$ autoload zmv
$ zmv '(<1->).jpg' '${(l:3::0:)1}.jpg'
# See above, but now only files with a filename >= 30 chars
$ autoload zmv
$ c=1 zmv "${(l:30-4::?:)}*.foo" '$((c++)).foo'
# Replace spaces in filenames with a underline
$ autoload zmv
$ zmv '* *' '$f:gs/ /_'
# Change the suffix from *.sh to *.pl
$ autoload zmv
$ zmv -W '*.sh' '*.pl'
# Add a "".txt" extension to all the files within ${HOME}
# ``-.'' is to only rename regular files or symlinks to regular files,
# ``D'' is to also rename hidden files (dotfiles))
$ autoload zmv
$ zmv -Q '/home/**/*(D-.)' '$f.txt'
# Or to only rename files that don't have an extension:
$ zmv -Q '/home/**/^?*.*(D-.)' '$f.txt'
# Recursively change filenames with characters ? [ ] / = + < > ; : " , - *
$ autoload zmv
$ chars='[][?=+<>;",*-]'
$ zmv '(**/)(*)' '$1${2//$~chars/%}'
# Removing single quote from filenames (recursively)
$ autoload zmv
$ zmv -Q "(**/)(*'*)(D)" "\$1\${2//'/}"
# When a new file arrives (named file.txt) rename all files in order to get (e. g.
# file119.txt becomes file120.txt, file118.txt becomes file119.txt and so on ending
# with file.txt becoming file1.txt
$ autoload zmv
$ zmv -fQ 'file([0-9]##).txt(On)' 'file$(($1 + 1)).txt'
# lowercase/uppercase all files/directories
$ autoload zmv
$ zmv '(*)' '${(L)1}' # lowercase
$ zmv '(*)' '${(U)1}' # uppercase
# Remove the suffix *.c from all C-Files
$ autoload zmv
$ zmv '(*).c' '$1'
# Uppercase only the first letter of all *.mp3 - files
$ autoload zmv
$ zmv '([a-z])(*).mp3' '${(C)1}$2.mp3'
# Copy the target `README' in same directory as each `Makefile'
$ autoload zmv
$ zmv -C '(**/)Makefile' '${1}README'
# Removing single quote from filenames (recursively)
$ autoload zmv
$ zmv -Q "(**/)(*'*)(D)" "\$1\${2//'/}"
# Rename pic1.jpg, pic2.jpg, .. to pic0001.jpg, pic0002.jpg, ..
$ autoload zmv
$ zmv 'pic(*).jpg' 'pic${(l:4::0:)1}.jpg'
$ zmv '(**/)pic(*).jpg' '$1/pic${(l:4::0:)2}.jpg' # recursively
Module-Examples (see zshmodules(1) for details)
zsh/pcre (require zmodload zsh/pcre)
Interface to the PCRE library
# Copy files of a certain period (date indicated in the filenames)
$ zmodload zsh/pcre
$ ls -d -- *(e:'[[ $REPLY -pcre-match pcre-regexp ]]':)
# or
$ m() { [[ $1 -pcre-match pcre-regexp ]] }
$ ls -d -- *(+m)
A builtin that can clone a running shell onto another terminal.
# Creates a forked instance of the current shell ($! is set to zero) and
# execute ``command'' on /dev/tty8 (for this example).
$ zmodload zsh/clone
$ clone /dev/tty8 && (($! == 0)) && exec command
Some date/time commands and parameters.
# Finding yesterdays date
$ zsh -c 'zmodload zsh/datetime
> strftime %c $((EPOCHSECONDS-86400))'
$ zmodload zsh/datetime
$ alias datereplacement='strftime "%Y-%m-%d" $EPOCHSECONDS'
$ export DATE=`datereplacement`
$ echo $DATE
# strip date from filename
$ $ zmodload zsh/datetime
$ setopt extendedglob
$ touch aaa_bbb_20041212_c.dat eee_fff_20051019_g.dat
$ strftime -s pattern '???_???_<0-%Y%m%d>_?.dat' $((EPOCHSECONDS - 365 * 24 * 60 * 60 / 2))
$ print -rl -- $~pattern
aaa_bbb_20041212_c.dat
$ print -rl -- $pattern
???_???_<0-20050815>_?.dat
# Search files size == 0, to be based on the file name containing a date rather than the "last
# modified" date of the file
$ zmodload -i zsh/datetime
$ strftime -s file "abc_de_%m%d%Y.dat" $((EPOCHSECONDS - 24 * 60 * 60 ))
$ files=(**/$file(N.L0))
$ (( $#files > 0 )) && print -rl -- $files | mailx -s "empty files" foo@bar.tdl
A builtin command interface to the stat system call.
# comparing file dates
$ zmodload zsh/stat
$ file1=foo
$ file2=bar
$ touch bar & sleep 5 & touch foo
$ echo $file1 is $(( $(stat +mtime $file2) - $(stat +mtime $file1) )) seconds older than $file2.
bar is 5 seconds older than foo
# list the files of a disk smaller than some other file
$ zmodload zsh/stat
$ stat -A max +size some-other-file
$ print -rl ./**/*(D.L-$max)
# List the top 100 biggest files in a disk
$ zmodload zsh/stat
$ ls -fld ./**/*(d`stat +device .`OL[1,100])
# Get only the user name and the file names from (like ls -l * | awk '{print $3" " $8}')
$ zmodload zsh/stat
$ for file; do
> stat -sA user +uid -- "$file" &&
> print -r -- "$user" "$file"
> done
# get the difference between actual bytes of file and allocated bytes of file
$ zmodload zsh/stat
$ print $(($(stat +block -- file) * 512 - $(stat +size -- file)))
# Find largest file
# ``D'' : to include dot files (d lowercase is for device)
# ``O'' : reverse Ordered (o lowercase for non-reverse order)
# ``L'' : by file Length (l is for number of links)
# ``[1]'': return only first one
$ zmodload zsh/stat
$ stat +size ./*(DOL[1])
# file size in bytes
$ zmodload zsh/stat
$ stat -L +size ~/.zshrc
4707
# Delete files in a directory that hasn't been accessed in the last ten days
# and send ONE mail to the owner of the files informing him/her of the files' deletion.
$ zmodload zsh/stat zsh/files
$ typeset -A f; f=()
$ rm -f /path/**/*(.a+10e{'stat -sA u +uidr $REPLY; f[$u]="$f[$u]$REPLY"'})
$ for user (${(k)f}) {print -rn $f[$user]|mailx -s "..." $user}
# Get a "ls -l" on all the files in the tree that are younger than a specified age
$ zmodload zsh/stat
$ for d (. ./**/*(N/m-2))
> print -r -- $'\n'$d: && cd $d && {
> for f (*(Nm-2om))
> stat -F '%b %d %H:%M' -LsAs -- $f &&
> print -r -- $s[3] ${(l:4:)s[4]} ${(l:8:)s[5]} \
> ${(l:8:)s[6]} ${(l:8:)s[8]} $s[10] $f ${s[14]:+-> $s[14]}
> cd ~-
> }
# get file creation date
$ zmodload zsh/stat
$ stat -F '%d %m %Y' +mtime ~/.zshrc
30 06 2004
$ stat -F '%D' +mtime ~/.zshrc
06/30/04
Some basic file manipulation commands as builtins.
# search a directory for files containing a certain string then copy those files to another directory.
$ zmodload zsh/files
$ IFS=$'\0'
$ cp $(grep -lZr foobar .) otherdirectory
Access to external files via a special associative array.
# grepping for two patterns
$ zmodload zsh/mapfile
$ pattern1="foo"
$ pattern2="bar foo"
$ print -l ./**/*(DN.e{'z=$mapfile[$REPLY] && [[ $z = *$pattern1* && $z = *$pattern2* ]]'})
# or a solution in combination with zsh/pcre
$ zmodload -i zsh/mapfile zsh/pcre
$ pattern1="foo"
$ pattern2="bar foo"
$ pcre_compile "(?s)(?=.*?$pattern1).*?$pattern2"
$ pcre_study
$ print -l ./**/*(DN.e{'pcre_match $mapfile[$REPLY]'})
# equivalent for ``less /etc/passwd | grep -v root''
$ zmodload zsh/mapfile
$ IFS=$'\n\n'
$ print -rl -- ${${=mapfile[/etc/passwd]}:#*root*}
# or - for case insensitive
$ setopt extendedglob
$ print -rl -- ${${=mapfile[/etc/passwd]}:#*(#i)root*}
# If a XML-file contains stuff like ``<TAGA/>'' and ``<TAGB/>'', number this empty tags
# (ones ending in '/>') so if encountered in the same order, the preceeding tags would become
# ``<TAGA/>1</TAGA>'' and ``<TAGB/>2</TAGB>''
$ zmodload zsh/mapfile
$ cnt=0
$ apfile[data.xml.new]=${(S)mapfile[data.xml]//\
> (#im)<TAGA>*<\/TAGA>/<TAGA>$((++cnt))<\/TAGA>}
# removing all files in users Maildir/new that contain ``filename="gone.src''
$ zmodload zsh/{files,mapfile}
$ rm -f /u1/??/*/Maildir/new/100*(.e{'[[ $mapfile[$REPLY] == *filename=\"gone.scr\"* ]]'})
# Grep out the Title from a postscript file and append that value to the end of
# the filename
$ autoload -U zmv
$ zmodload zsh/mapfile
$ zmv '(*).ps' '$1-${${${mapfile[$f]##*%%Title: }%% *}//[^a-zA-Z0-9_]/}.ps'
Standard scientific functions for use in mathematical evaluations.
$ zmodload zsh/mathfunc
$ echo $(( sin(1/4.0)**2 + cos(1/4.0)**2 - 1 ))
-1.1102230246251565e-16
$ echo $(( pi = 4.0 * atan(1.0) ))
3.1415926535897931
$ echo $(( f = sin(0.3) ))
0.29552020666133955
$ print $((1e12 * rand48()))
847909677310.23413
$ print $(( rand48(seed) ))
0.01043488334700271
Interface to the termcap database.
$ zmodload -ab zsh/termcap echotc
$ GREEN=`echotc AF 2`
$ YELLOW=`echotc AF 3`
$ RED=`echotc AF 1`
$ BRIGHTRED=`echotc md ; echotc AF 1`
$ print -l ${GREEN}green ${YELLOW}yellow ${RED}red ${BRIGHTRED}brightred
A builtin for starting a command in a pseudo-terminal.
$ zmodload zsh/zpty
$ zpty PW passwd $1
$ zpty PW passwd $1
# ``-r'': read the output of the command name.
# ``z'' : Parameter
$ zpty -r PW z '*password:'
# send the to command name the given strings as input
$ zpty -w PW $2
$ zpty -r PW z '*password:'
$ zpty -w PW $2
# The second form, with the -d option, is used to delete commands
# previously started, by supplying a list of their names. If no names
# are given, all commands are deleted. Deleting a command causes the HUP
# signal to be sent to the corresponding process.
$ zpty -d PW
Manipulation of Unix domain sockets.
# ``-l'': open a socket listening on filename
# ``-d'': argument will be taken as the target file descriptor for the
# connection
# ``3'' : file descriptor. See ``A User's Guide to the Z-Shell''
# (3.7.2: File descriptors)
$ zmodload zsh/net/socket
$ zsocket -l -d 3
# ``-a'': accept an incoming connection to the socket
$ zsocket -a -d 4 3
$ zsocket -a -d 5 3 # accept a connection
$ echo foobar >&4
$ echo barfoo >&5
$ 4>&- 5>&- 3>&
A builtin FTP client.
$ autoload -U zfinit
$ zfinit
$ zfparams www.example.invalid myuserid mypassword
$ zfopen
$ zfcd tips
$ zfls -l zshtips.html
$ zfput zshtips.html
$ zfls -l zshtips.html
# Automatically transfer files using FTP with error checking
$ autoload -U zfinit ; zfinit
$ zftp open host.name.invalid user passwd || exit
$ zftp get /remote/file > /local/file; r=$?
$ zftp close && exit r
# compress and ftp on the fly
$ autoload -U zfinit ; zfinit
$ zftp open host.name.invalid user password
$ zftp get $file | bzip2 > ${file}.bz2
$ zftp close
# Recursice ``get''
$ autoload -U zfinit ; zfinit
$ zfanon cr.yp.to
$ zfcd daemontools
$ for file in `zfls` ; do
> zfget $file
$ done
$ zfclose
# Upload all regular files in $HOME/foobar (recursive) that are newer than two hours
# to ftp.foobar.invalid/path/to/upload
$ autoload -U zfinit ; zfinit
$ zfopen ftp.foobar.invalid/path/to/upload
$ cd $HOME/foobar
$ zfput -r **/*(.mh-2)
$ zfclose
# long list of files on a ftp
$ autoload -U zfinit ; zfinit
$ zfopen some-host
$ zfcd /some/remote/Dir
$ cd /some/local/Dir
# If the list.txt is located on the remote host, change to
# zfget ${(f)"$(zftp get /path/to/remote/list.txt)"}
$ zfget ${(f)"$(cat list.txt)"}
$ zfclose
Block and return when file descriptors are ready.
# It's similar to
,----
| $ sg=$(stty -g)
| $ stty -icanon min 0 time 50
| $ read yesno
| $ stty "$sg"
| $ case "$yesno" in
| > yes) command1;;
| > *) command2;;
| > esac
`----
$ zmodload zsh/zselect
$ if zselect -t 500 -r 0 && read yesno && [ yes = "$yesno" ]; then
> command1
> else
> command1
> fi
- Primary site
- http://www.zsh.org
- Project-page
- http://sourceforge.net/projects/zsh/
- Z shell page at sunsite.dk
- http://zsh.sunsite.dk/
- Mailinglistarchive
- http://www.zsh.org/mla/
- ZSH-FAQ
- http://www.zsh.org/FAQ/
- Userguide
- http://zsh.sunsite.dk/Guide/
- ZSH-Wiki
- http://www.zshwiki.org/
- Die Zsh als interaktive Shell
- http://cssun.rrze.uni-erlangen.de/~sipakale/zshreferat.html
- A short introduction from BYU
- http://docs.cs.byu.edu/index.php/ZSH
- Mouse-Support ;)
- http://stchaz.free.fr/mouse.zsh
- Shell Corner: Zsh Suite of "keeper" Functions
- http://www.unixreview.com/documents/s=9513/ur0501a/ur0501a.htm
- The Z Shell (A Fan Page)
- http://www.princeton.edu/~kmccarty/zsh.html
- Making the Transition to Zsh
- http://www.linux-mag.com/cgi-bin/printer.pl?issue=2002-05&article=power
- Curtains up: introducing the Z shell
- http://www-128.ibm.com/developerworks/linux/library/l-z.html?dwzone=linux
- Die Zsh-Liebhaber-Seite
- http://www.infodrom.north.de/~matthi/zsh/
-
- ZSH-Liebhaberseite
- http://michael-prokop.at/computer/tools_zsh_liebhaber.html
- ZSH-Seite von Michael Prokop
- http://www.michael-prokop.at/computer/tools_zsh.html
- A Case for the Z Shell on http://www.daemonnews.org/
- http://ezine.daemonnews.org/199910/zsh.html
- ZSH-Section from Dotfiles.com
- http://www.dotfiles.com/index.php3?app_id=4
- Writing Zsh Completion Functions
- http://www.linux-mag.com/2002-07/power_01.html
- ZSH Prompt introduction
- http://aperiodic.net/phil/prompt/
- Adam's ZSH page
- http://www.adamspiers.org/computing/zsh/
- Zzappers Best of ZSH Tips
- http://www.rayninfo.co.uk/tips/zshtips.html
$Id: zsh/index..html,v 1.1 2002/10/04 20:18:12 dope Exp dope $
Send comments to zsh@strcat.de
Last modified: [ 2004-09-07 18:43:38 ]