Cleanup of spaces at end of lines, Add missing l:=o_log to first code example
[zsh-lovers.git] / zsh-lovers.1.txt
1 ZSH-LOVERS(1)
2 =============
3
4 NAME
5 ----
6 zsh-lovers - tips, tricks and examples for the Z shell
7
8 SYNOPSIS
9 --------
10 Just read it. ;-)
11
12 OVERVIEW
13 --------
14 Whenever we look at the zsh manual we wonder why there are no examples or those
15 simply things in (shell) life.  The zsh contains many features, but there was no
16 manpage with some examples (like procmailex(5)).  That's why we wrote this
17 manpage.
18
19 Most of the tricks and oneliner come from the mailinglists zsh-users,
20 zsh-workers, google, newsgroups and from ourself.  See section *LINKS* for
21 details.
22
23 Note: This manpage (zsh-lovers(1)) is *not* an offical part of the Z shell! It's
24 just a just for fun - manpage ;) +
25 For comments, bugreports and feedback take a quick look at the section *BUGS*.
26
27 SHELL-SCRIPTING
28 ---------------
29 This section provides some examples for often needed shellscript-stuff. Notice
30 that you should not use otherwise most examples won't work. +
31 Parse options in shellscripts. Example taken from ZWS by Adam Chodorowski
32 (http://www.chodorowski.com/projects/zws/[]):
33 ----------------------------------------------
34 parse_options()
35 {
36     o_port=(-p 9999)
37     o_root=(-r WWW)
38     o_log=(-d ZWS.log)
39
40     zparseopts -K -- p:=o_port r:=o_root l:=o_log h=o_help
41     if [[ $? != 0 || "$o_help" != "" ]]; then
42         echo Usage: $(basename "$0") "[-p PORT] [-r DIRECTORY]"
43         exit 1
44     fi
45
46     port=$o_port[2]
47     root=$o_root[2]
48     log=$o_log[2]
49
50     if [[ $root[1] != '/' ]]; then root="$PWD/$root"; fi
51 }
52 # now use the function:
53 parse_options $*
54 ----------------------------------------------
55
56 EXAMPLES
57 --------
58 Available subsections are *Aliases*, *Completion*, *Unsorted/Misc examples*,
59 *(Recursive) Globbing - Examples*, *Modifiers usage*, *Redirection-Examples*,
60 *ZMV-Examples* and *Module-Examples*.
61
62 ALIASES
63 ~~~~~~~
64 Suffix aliases are supported in zsh since version 4.2.0. Some examples:
65 -----------------
66 alias -s tex=vim
67 alias -s html=w3m
68 alias -s org=w3m
69 -----------------
70 Now pressing return-key after entering 'foobar.tex' starts vim with
71 foobar.tex. Calling a html-file runs browser w3m. 'www.zsh.org' and pressing
72 enter starts w3m with argument www.zsh.org. +
73 Global aliases can be used anywhere in the command line. Example:
74 ----------------------
75 $ alias -g C='| wc -l'
76 $ grep alias ~/.zsh/* C
77 443
78 ----------------------
79 Some more or less useful global aliases (choose whether they are useful  or not
80 for you on your own):
81
82 --------------------------------------------------------
83 alias -g ...='../..'
84 alias -g ....='../../..'
85 alias -g .....='../../../..'
86 alias -g CA="2>&1 | cat -A"
87 alias -g C='| wc -l'
88 alias -g D="DISPLAY=:0.0"
89 alias -g DN=/dev/null
90 alias -g ED="export DISPLAY=:0.0"
91 alias -g EG='|& egrep'
92 alias -g EH='|& head'
93 alias -g EL='|& less'
94 alias -g ELS='|& less -S'
95 alias -g ETL='|& tail -20'
96 alias -g ET='|& tail'
97 alias -g F=' | fmt -'
98 alias -g G='| egrep'
99 alias -g H='| head'
100 alias -g HL='|& head -20'
101 alias -g Sk="*~(*.bz2|*.gz|*.tgz|*.zip|*.z)"
102 alias -g LL="2>&1 | less"
103 alias -g L="| less"
104 alias -g LS='| less -S'
105 alias -g MM='| most'
106 alias -g M='| more'
107 alias -g NE="2> /dev/null"
108 alias -g NS='| sort -n'
109 alias -g NUL="> /dev/null 2>&1"
110 alias -g PIPE='|'
111 alias -g R=' > /c/aaa/tee.txt '
112 alias -g RNS='| sort -nr'
113 alias -g S='| sort'
114 alias -g TL='| tail -20'
115 alias -g T='| tail'
116 alias -g US='| sort -u'
117 alias -g VM=/var/log/messages
118 alias -g X0G='| xargs -0 egrep'
119 alias -g X0='| xargs -0'
120 alias -g XG='| xargs egrep'
121 alias -g X='| xargs'
122 --------------------------------------------------------
123
124 COMPLETION
125 ~~~~~~~~~~
126 See also man 1 zshcompctl zshcompsys zshcompwid. zshcompctl is the old
127 style of zsh programmable completion, zshcompsys is the new completion
128 system, zshcompwid are the zsh completion widgets.
129
130 Some functions, like _apt and _dpkg, are very slow. You can use a cache
131 in order to proxy the list of  results  (like  the  list  of  available
132 debian packages) Use a cache:
133 ---------------------------------------------------------------------------------------------------
134 zstyle ':completion:*' use-cache on
135 zstyle ':completion:*' cache-path ~/.zsh/cache
136 ---------------------------------------------------------------------------------------------------
137
138 Prevent CVS files/directories from being completed:
139 ---------------------------------------------------------------------------------------------------
140 zstyle ':completion:*:(all-|)files' ignored-patterns '(|*/)CVS'
141 zstyle ':completion:*:cd:*' ignored-patterns '(*/)#CVS'
142 ---------------------------------------------------------------------------------------------------
143
144 Fuzzy matching of completions for when you mistype them:
145 ---------------------------------------------------------------------------------------------------
146 zstyle ':completion:*' completer _complete _match _approximate
147 zstyle ':completion:*:match:*' original only
148 zstyle ':completion:*:approximate:*' max-errors 1 numeric
149 ---------------------------------------------------------------------------------------------------
150
151 And  if  you  want  the  number  of  errors  allowed by _approximate to
152 increase with the length of what you have typed so far:
153 ---------------------------------------------------------------------------------------------------
154 zstyle -e ':completion:*:approximate:*' \
155         max-errors 'reply=($((($#PREFIX+$#SUFFIX)/3))numeric)'
156 ---------------------------------------------------------------------------------------------------
157
158 Ignore completion functions for commands you don't have:
159 ---------------------------------------------------------------------------------------------------
160 zstyle ':completion:*:functions' ignored-patterns '_*'
161 ---------------------------------------------------------------------------------------------------
162
163 With helper functions like:
164 ---------------------------------------------------------------------------------------------------
165 xdvi() { command xdvi ${*:-*.dvi(om[1])} }
166 ---------------------------------------------------------------------------------------------------
167
168 you can avoid having to complete at all in many cases, but if  you  do,
169 you  might want to fall into menu selection immediately and to have the
170 words sorted by time:
171 ---------------------------------------------------------------------------------------------------
172 zstyle ':completion:*:*:xdvi:*' menu yes select
173 zstyle ':completion:*:*:xdvi:*' file-sort time
174 ---------------------------------------------------------------------------------------------------
175
176 Completing process IDs with menu selection:
177 ---------------------------------------------------------------------------------------------------
178 zstyle ':completion:*:*:kill:*' menu yes select
179 zstyle ':completion:*:kill:*'   force-list always
180 ---------------------------------------------------------------------------------------------------
181
182 If you end up using a directory  as  argument,  this  will  remove  the
183 trailing slash (usefull in ln)
184 ---------------------------------------------------------------------------------------------------
185 zstyle ':completion:*' squeeze-slashes true
186 ---------------------------------------------------------------------------------------------------
187
188 cd will never select the parent directory (e.g.: cd ../<TAB>):
189 ---------------------------------------------------------------------------------------------------
190 zstyle ':completion:*:cd:*' ignore-parents parent pwd
191 ---------------------------------------------------------------------------------------------------
192
193 UNSORTED/MISC examples
194 ~~~~~~~~~~~~~~~~~~~~~~
195 Hint: A list of valid glob Qualifiers can be found in zshexpn(1).
196 See ``man 1 zshexpn | less -p'' Qualifiers for details.
197
198 -------------------------------------------------------------------------------
199 # test if a parameter is numeric
200   $ if [[ $1 == <-> ]] ; then
201          echo numeric
202     else
203          echo non-numeric
204     fi
205
206 # Show me all the .c files for which there doesn't exist a .o file.
207   $ c=(*.c) o=(*.o(N)) eval 'ls ${${c:#(${~${(j:|:)${o:r}}}).c}:?done}'
208
209 # All files in /var/ that are not owned by root
210   $ ls -ld /var/*(^u:root)
211
212 # All files for which the owner hat read and execute permissions
213   $ echo *(f:u+rx:)
214
215 # The same, but also others dont have execute permissions
216   $ echo *(f:u+rx,o-x:)
217
218 # brace expansion - example
219   $ X=(A B C)
220   $ Y=(+ -)
221   $ print -r -- $^X.$^Y
222   A.+ A.- B.+ B.- C.+ C.-
223
224 # Fetch the newest file containing the string 'fgractg*.log' in the
225 # filename and contains the string 'ORA-' in it
226   $ file=(fgractg*.log(Nm0om[1]))
227   $ (($#file)) && grep -l ORA- $file
228   # without Zsh
229   $ files=$( find . -name . -o -prune -name 'fgractg*>log' -mtime 0 -print )
230   > if [ -n "$files" ]; then
231   >    IFS='
232   > '
233   > set -f
234   > file=$(ls -td $files | head -1)
235   > grep -l ORA- "$file"
236   > fi
237
238 # keep specified number of child processes running until entire task finished
239   $ zsh -c 'sleep 1 & sleep 3 & sleep 2& print -rl -- $jobtexts'
240
241 # Remove zero length and .bak files in a directory
242   $ rm -i *(.L0) *.bak(.)
243
244 # print out files that dont have extensions
245   $ printf '%s\n' ^?*.*
246   $ printf '%s\n' ^?*.[^.]*(D)
247   $ ls -d -- ^?*.*(D)
248
249 # Finding files which does not contain a specific string
250   $ print -rl file* | comm -2 -3 - <(grep -l string file*)'
251   $ for f (file*(N)) grep -q string $f || print -r $f'
252
253 # Show/Check whether a option is set or not. It works both with $options as
254 # with $builtins
255   $ echo $options[correct]
256   off
257   $ $options[zle]
258   on
259
260 # Count the number of directories on the stack
261   $ print $((${${(z)${(f)"$(dirs -v)"}[-1]}[1]} + 1)) # or
262   $ dirs -v | awk '{n=$1}END{print n+1}'
263
264 # Matching all files which do not have a dot in filename
265   $ ls *~*.*(.)
266
267 # Show only the ip-address from ``ifconfig device''
268   # ifconfig from net-tools (Linux)
269   $ print ${${$(LC_ALL=C /sbin/ifconfig eth0)[7]}:gs/addr://}
270   # ifconfig from 4.2BSD {Free,Net,Open}BSD
271   $ print ${$(/sbin/ifconfig tun0)[6]}
272
273 # Ping all the IP addresses in a couple of class C's or all hosts
274 # into /etc/hosts
275   $ for i in {1..254}; do ping -c 1 192.168.13.$i; done
276   or
277   $ I=1
278   $ while ( [[ $I -le 255 ]] ) ; do ping -1 2 150.150.150.$I; let I++; done
279   or
280   $ for i in $(sed 's/#.*//' > /etc/hosts | awk '{print $2}')
281   : do
282   :    echo "Trying $i ... "
283   :    ping -c 1 $i ;
284   :    echo '============================='
285   : done
286
287 # load all available modules at startup
288   $ typeset -U m
289   $ m=()
290   $ for md ($module_path) m=($m $md/**/*(*e:'REPLY=${REPLY#$md/}'::r))
291   $ zmodload -i $m
292
293 # Rename all files within a directory such that their names get a numeral
294 # prefix in the default sort order.
295   $ i=1; for j in *; do mv $j $i.$j; ((i++)); done
296   $ i=1; for f in *; do mv $f $(echo $i | \
297     awk '{ printf("%03d", $0)}').$f; ((i++)); done
298   $ integer i=0; for f in *; do mv $f $[i+=1].$f; done
299
300 # Find (and print) all symbolic links without a target within the current
301 # dirtree.
302   $ $ file **/*(D@) | fgrep broken
303   $ for i in **/*(D@); [[ -f $i || -d $i ]] || echo $i
304   $ echo **/*(@-^./=%p)
305   $ print -l **/*(-@)
306
307 # List all plain files that do not have extensions listed in `fignore'
308   $ ls **/*~*(${~${(j/|/)fignore}})(.)
309   # see above, but now omit executables
310   $ ls **/*~*(${~${(j/|/)fignore}})(.^*)
311
312 # Print out files that dont have extensions (require *setopt extendedglob*
313 # and *setopt dotglob*)
314   $ printf '%s\n' ^?*.*
315
316 # List files in reverse order sorted by name
317   $ print -rl -- *(On)
318   or
319   $ print -rl -- *(^on)
320
321 # Synonymic to ``ps ax | awk '{print $1}'''
322   $ print -l /proc/*/cwd(:h:t:s/self//)
323
324 # Get the PID of a process (without ``ps'', ``sed'', ``pgrep'', ..
325 # (under Linux)
326   $ pid2 () {
327   >   local i
328   >   for i in /proc/<->/stat
329   > do
330   >   [[ "$(< $i)" = *\((${(j:|:)~@})\)* ]] && echo $i:h:t
331   > done
332   > }
333
334 # for X in 'n' 'o' 'p' 'q' 'r' 's' 't' 'u' 'v' 'w' 'x' 'y'; do ...
335   $ for (( i = 36#n; i <= 36#y; i++ )); do
336   >   print ${$(([##36]i)):l}
337   > done
338 # or in combination with ``dc''
339   $ print {$((##n))..$((##y))}P\ 10P | dc
340 # or with ``eval''
341   $ eval print '${$(([##36]'{$((36#n))..$((36#y))}')):l}'
342
343 # foreach in one line of shell
344   $ for f (*) print -r -- $f
345
346 # copy a directory recursively without data/files
347   $ dirs=(**/*(/))
348   $ cd -- $dest_root
349   $ mkdir -p -- $dirs
350 # or without zsh
351   $ find . -type d -exec env d="$dest_root" \
352     sh -c ' exec mkdir -p -- "$d/$1"' '{}' '{}' \;
353
354 # If `foo=23'', then print with 10 digit with leading '0'.
355   $ foo=23
356   $ print ${(r:10::0:)foo}
357
358 # find the name of all the files in their home directory that have
359 # more than 20 characters in their file names
360   print -rl $HOME/${(l:20::?:)~:-}*
361
362 # Save arrays
363   $ print -r -- ${(qq)m} > $nameoffile      # save it
364   $ eval "m=($(cat -- $nameoffile)"            # or use
365   $ m=("${(@Q)${(z)"$(cat -- $nameoffile)"}}") # to restore it
366
367 # get a "ls -l" on all the files in the tree that are younger than a
368 # specified age (e.g "ls -l" all the files in the tree that where
369 # modified in the last 2 days)
370   $ ls -tld **/*(m-2)
371 # This will give you a listing 1 file perl line (not Ã  la ls -R).
372 # Think of an easy way to have a "ls -R" style output with
373 # only files newer than 2 day old.
374   $ for d (. ./**/*(/)) {
375   >   print -r -- $'\n'${d}:
376   >   cd $d && {
377   >       l=(*(Nm-2))
378   >       (($#l)) && ls -ltd -- $l
379   >       cd ~-
380   >   }
381   > }
382 # If you also want directories to be included even if their mtime
383 # is more than 2 days old:
384   $ for d (. ./**/*(/)) {
385   >   print -r -- $'\n'${d}:
386   >   cd $d && {
387   >      l=(*(N/,m-2))
388   >      (($#l)) && ls -ltd -- $l
389   >      cd ~-
390   >   }
391   > }
392 # And if you want only the directories with mtime < 2 days to be listed:
393   $ for d (. ./**/*(N/m-2)) {
394   >   print -r -- $'\n'${d}:
395   >   cd $d && {
396   >      l=(*(Nm-2))
397   >      (($#l)) && ls -ltd -- $l
398   >      cd ~-
399   >   }
400   > }
401
402 # print 42 ``-''
403   $ echo ${(l:42::-:)}
404 # or use ``$COLUMS''
405   $ echo ${(l:$COLUMNS::-:)}
406 # and now with colors (require autoload colors ;colors)
407   $ echo "$bg[red]$fg[black]${(l:42::-:)}"
408
409 # Redirect STDERR to a command like xless without redirecting STDOUT as well.
410   $ foo 2>>(xless)
411 # but this executes the command asynchronously. To do it synchronously:
412   $ { { foo 1>&3 } 2>&1 | xless } 3>&1
413
414 # Rename all MP3-Files from name with spaces.mp3 to Name With Spaces.mp3
415   $ for i in *.mp3; do
416   >     mv $i ${${(C)i}:s/Mp3/mp3/}
417   > done
418
419 # Match file names containing only digits and ending with .xml (require
420 # *setopt kshglob*)
421   $ ls -l [0-9]##.xml
422   $ ls -l <0->.xml
423
424 # Remove all "non txt" files
425   $ rm ./^*.txt
426
427 # Move 200 files from a directory into another
428   $ mv -- *([1,200]) /another/Dir
429
430 # Convert images (foo.gif => foo.png):
431   $ for i in **/*.gif; convert $i $i:r.png
432
433 # convert a collection of mp3 files to wave or cdr,
434 # e.g. file.wav -> file.mp3)
435   $ for i (./*.mp3){mpg321 --w - $i > ${i:r}.wav}
436
437 # Download with LaTeX2HTML  created Files (for example the ZSH-Guide):
438   $ for f in http://zsh.sunsite.dk/Guide/zshguide{,{01..08}}.html; do
439   >     lynx -source $f >${f:t}
440   > done
441
442 # Move all files in dir1 and dir2 that have line counts greater than 10 to
443 # another directory say "/more10"
444   $ mv dir[12]/**/*.cr(-.e{'((`wc -l < $REPLY` > 10))'}) /more10
445
446 # Make with dpkg a master-list of everyfile that it has installed
447   $ diff <(find / | sort) <(cat /var/lib/dpkg/info/*.list | sort)
448
449 # Replace this fucking Escape-Sequences:
450   $ autoload colors ; colors
451   $ print "$bg[cyan]$fg[blue]You are a idiot" >> /dev/pts/3
452
453 # Get ASCII value of a character
454   $ char=N ; print $((#char))
455
456 # Filename "Erweiterung"
457 # Note: The (N) says to use the nullglob option for this particular
458 # glob pattern.
459   $ for i in *.o(N); do
460   >     rm $i
461   > done
462
463 # Rename files; i. e. FOO to foo and bar to BAR
464   $ for i in *(.); mv $i ${i:l} # `FOO' to `foo'
465   $ for i in *(.); mv $i ${i:u} # `bar to `BAR'
466
467 # Show all suid-files in $PATH
468   $ ls -latg ${(s.:.)PATH} | grep '^...s'
469 # or more complex ;)
470   $ print -l ${^path}/*(Ns,S)
471 # or show only executables with a user given pattern
472   $ print -l ${^path}/*vim*(*N)
473
474 # gzip files when containing a certain string
475   $ gzip ${(ps:\0:)"$(grep -lZ foobar ./*.txt(.))"}
476
477 # A small  one-liner, that reads from stdin and prints to stdout the first
478 # unique line i. e. does not print lines that have been printed before
479 # (this is similar to the unique command, but unique can only handle
480 # adjacent lines).
481   $ IFS=$'\n\n'; print -rl -- ${(Oau)${(Oa)$(cat file;echo .)[1,-2]}}
482
483 # Lists every executable in PATH
484   $ print -l ${^path}/*(-*N)
485
486 # Match all .c files in all subdirectories, _except_ any SCCS subdirectories?
487   $ ls **/*.c~(*/)#SCCS/*
488
489 # List all `README' - files case-insensitive with max. one typo
490   $ ls **/*(#ia2)readme
491
492 # case insensitive checking for variables
493   $ if [[ $OSTYPE == (#i)LINUX*(#I) ]]; then
494   >    echo "Penguin on board."
495   > else
496   >    echo "Not a Linux."
497   > fi
498 -------------------------------------------------------------------------------
499
500 (Recursive) Globbing - Examples
501 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
502 A list of valid glob Qualifiers can be found in zshexpn(1). *Note:*
503 \*\*/ is equivalent to (*/)#! For example:
504 -------------------------------------------------------------------------------
505 $ print (*/)#zsh_us.ps
506 zsh-4.2.3/Doc/zsh_us.ps
507 $ print **/zsh_us.ps
508 zsh-4.2.3/Doc/zsh_us.ps
509 -------------------------------------------------------------------------------
510
511 -------------------------------------------------------------------------------
512 # Search for `README' in all Subdirectories
513   $ ls -l **/README
514
515 # find directories that contain both "index.php" and "index.html", or in
516 # general, directories that contain more than one file matching "index.*"
517   $ ls **/*(D/e:'[[ -e $REPLY/index.php && -e $REPLY/index.html ]]':)
518   # or
519   $ ls **/*(D/e:'l=($REPLY/index.*(N)); (( $#l >= 2 ))':)
520
521 # Find command to search for directory name instead of basename
522   $ print -rl /**/*~^*/path(|/*)
523   # or - without Zsh
524   $ find / | grep -e /path/ -e '/path$'
525
526 # Print he path of the directories holding the ten biggest C regular files
527 # in the current directory and subdirectories.
528   $ print -rl -- **/*.c(D.OL[1,10]:h) | sort -u
529
530 # Find files with size == 0 and send a mail
531   $ files=(**/*(ND.L0m+0m-2))
532   > (( $#files > 0 )) && print -rl -- $files | \
533     mailx -s "empty files" foo@bar.tdl
534
535 # recursive chmod
536   $ chmod 700 **/(.) # Only files
537   $ chmod 700 **/(/) # Only directories
538
539 # print out all of the files in that directory in 2 columns
540   $ print -rC2 -- ${1:[...]}/*(D:t)
541 #            ^- number ob columns
542 # or - if you feel concerned about special characters - use
543   $ list=(${1:[...]}/*(ND:t))
544   $ (($#list)) && print -rC2 -- ${(V)list}
545
546 # Search all files in /home/*/*-mail/ with a setting ``chmod -s'' flag
547 # (recursive, include  dotfiles) remove the setgid/setuid flag and print
548 # a message
549   $ chmod -s /home/*/*-mail(DNs,S) /home/*/*-mail/**/*(DNs,S))
550 # or with a small script
551   $ for file (/home/*/*-mail(DNs,S) /home/*/*-mail/**/*(DNs,S)) {
552   >    print -r -- $file
553   >    chmod -s $file && print -r fixed $file
554   > }
555 # or use ``zargs'' (require autoload zargs) prevent the arg list too
556 # long error
557   $ zargs /home/*/*-mail(DNs,S) /home/*/*-mail/**/*(DNs,S)) -- chmod -s
558
559 # List files beginning at `foo23' upwards (foo23, foo24, foo25, ..)
560   $ ls -l foo<23->
561
562 # get all files that begin with the date strings from June 4 through
563 # June 9 of 2004
564   $ ls -l 200406{04..10}*(N)
565 # or if they are of the form 200406XX (require ``setopt extended_glob''
566   $ ls -l 200306<4-10>.*
567
568 # remove spaces from filenames
569   $ for a in ./**/*\ *(Dod); do mv $a ${a:h}/${a:t:gs/ /_}; done
570
571 # Show only all *.c and *.h - Files
572   $ ls -l *.(c|h)
573
574 # Show only all *.c - files and ignore `foo.c'
575   $ ls *.c~foo.c
576
577 # show data to *really* binary format
578   $ zsh -ec 'while {} {printf %.8x $n;repeat 8 \
579   > {read -ku0 a printf \ %.8d $(([##2]#a))};print;((n+=8))}' < binary
580
581 # Show only world-readable files
582   $ ls -l *(R)
583
584 # List files in the current directory are not writable by the owner
585   $ print -l ~/*(ND.^w)
586
587 # find and delete the files which are older than a given parameter
588 # (seconds/minutes/hours)
589   # deletes all regular file in /Dir that are older than 3 hours
590    $ rm -f /Dir/**/*(.mh+3)
591   # deletes all symlinks in /Dir that are older than 3 minutes
592    $ rm -f /Dir/**/*(@mm+3)
593   # deletes all non dirs in /Dir that are older than 30 seconds
594    $ rm -f /Dir/**/*(ms+30^/)
595   # deletes all folders, sub-folders and files older than one hour
596    $ rm ./**/*(.Dmh+1,.DL0)
597   # deletes all files more than 6 hours old
598    $ rm -f **/*(mh+6)
599   # removes all files but the ten newer ones (delete all but last 10
600   # files in a directory)
601    $ rm ./*(Om[1,-11])
602  Note: If you get a arg list too long, you use the builtin rm. For
603        example:
604    $ zmodload zsh/files ; rm -f **/*(mh+6)
605   or use the zargs function:
606    $ autoload zargs ; zargs **/*(mh+6) -- rm -f
607
608 # A User's Guide to the Z-Shell /5.9: Filename Generation and Pattern
609 # Matching find all files in all subdirectories, searching recursively,
610 # which have a given name, case insensitive, are at least 50 KB large,
611 # no more than a week old and owned by the root user, and allowing up
612 # to a single error in the spelling of the name. In fact, the required
613 # expression looks like this:
614   $ ls **/(#ia1)name(LK+50mw-1u0)
615
616 # Change the UID from 102 to 666
617   $ chown 666 **/*(u102)
618
619 # List all files which have not been updated since last 10 hours
620   $ print -rl -- *(Dmh+10^/)
621
622 # delete only the oldest file in a directory
623   $ rm ./*filename*(Om[1])
624
625 # Sort the output from `ls -l' by file size
626   $ ls -fld *(OL)
627
628 # find most recent file in a directory
629   $ setopt dotglob ; print directory/**/*(om[1])
630
631 # Show only empty files which nor `group' or `world writable'
632   $ ls *(L0f.go-w.)
633
634 # find - and list - the ten newest files in directories and subdirs
635 # (recursive)
636   $ print -rl -- **/*(Dom[1,10])
637
638 # Print only 5 lines by "ls" command (like ``ls -laS | head -n 5'')
639   $ ls -fl *(DOL[1,5])
640
641 # display the 5-10 last modified files
642   $ print -rl -- /path/to/dir/**/*(D.om[5,10])
643
644 # find all files without a valid owner
645   $ chmod someuser /**/*(D^u:${(j.:u:.)${(f)"$(</etc/passwd)"}%%:*}:)
646
647 # find all the empty directories in a tree
648   $ for f in ***/*(/l2); do foo=($f/*(N)); [[ -z $foo ]] && print $f; done
649 # Note:Since Zsh 4.2.1 the glob qualifier F indicates a non-empty directory.
650 # Hence *(F) indicates all subdirectories with entries, *(/^F) means all
651 # subdirectories with no entries.
652   $ ls -ld *(/^F)
653
654 # remove empty directories afterwards
655   $ rmdir ./**/*(/od) 2> /dev/null
656
657 # Show only files are owned from group `users'
658   $ ls -l *(G[users])
659
660 -------------------------------------------------------------------------------
661
662 Modifiers usage
663 ~~~~~~~~~~~~~~~
664 Modifiers are a powerful mechanism that let you modify the results
665 returned by parameter, filename and history expansion. See zshexpn(1)
666 for details.
667 -------------------------------------------------------------------------------
668 # Remove a trailing pathname component, leaving the head. This works like
669 # `dirname'.
670   $ echo =ls(:h)
671   /bin
672
673 # Remove all leading pathname components, leaving the tail. This works
674 # like `basename'.
675   $ echo =ls(:t)
676   ls
677
678 # Remove the suffix from each file (*.sh in this example)
679    $f:e is $f file extension
680    :h --> head (dirname)
681    :t --> tail (basename)
682    :r --> rest (extension removed)
683   $ for f (*.sh) mv $f $f:r
684
685 # Remove a filename extension of the form `.xxx', leaving the root name.
686   $ echo $PWD
687   /usr/src/linux
688   $ echo $PWD:t
689   linux
690
691 # Remove all but the extension.
692   $ foo=23.42
693   $ echo $foo
694   23.42
695   $ echo $foo:e
696   42
697
698 # Print the new command but do not execute it. Only works with history
699 # expansion.
700   $ echo =ls(:h)
701   /bin
702   $ !echo:p
703   $ echo =ls(:h)
704
705 # Quote the substituted words, escaping further substitutions.
706   $ bar="23'42"
707   $ echo $bar
708   23'42
709   $ echo $bar:q
710   23\'42
711
712 # Convert the words to all lowercase.
713   $ bar=FOOBAR
714   $ echo $bar
715   FOOBAR
716   $ echo $bar:l
717   foobar
718
719 # Convert the words to all uppercase.
720   $ bar=foobar
721   $ echo $bar
722   foobar
723   $ echo $bar:u
724   FOOBAR
725
726 # convert 1st char of a word to uppercase
727   $ foo="one two three four"
728   $ print -r -- "${(C)var}"
729   One Two Three Four
730 -------------------------------------------------------------------------------
731
732 Redirection-Examples
733 ~~~~~~~~~~~~~~~~~~~~
734 See zshmisc(1) for more informations (or less ${^fpath}/zmv(N))
735
736 -------------------------------------------------------------------------------
737 # Append `exit 1' at the end of all *.sh - files
738   $ echo "exit 1" >> *.sh
739
740 # adding files to foobar.tar.gz
741   $ eval set =(gunzip < foobar.tar.gz) '
742      tar rf $1 additional.txt &&gzip < $1 > foobar.tar.gz'
743
744 # Redirect output to a file AND display on screen
745   $ foobar >&1 > file1 > file2 > ..
746
747 # pipe single output to multiple inputs
748   $ zcat foobar.Z >> (gzip -9 > file1.gz) \
749       >> (bzip2 -9 > file1.bz2) \
750       >> (acb --best > file1.acb)
751
752 # Append /etc/services at the end of file `foo' and `bar'
753   $ cat /etc/services >> foo >> bar
754
755 # Pipe STDERR
756   $ echo An error >&2 2>&1 | sed -e 's/A/I/'
757
758 # send standard output of one process to standard input of several processes
759 # in the pipeline
760   $ setopt multios
761   $ process1 > >(process1) > >(process2)
762
763 # initializing a variable and simultaneously keeping terminal output
764   $ setopt multios
765   $ { a=$(command >&1 >& 3 3 > &- 2>&1);} 3>&1
766
767 # redirect stderr two times
768   $ setopt multios ; program 2> file2 > file1 2>&1
769
770 # Duplicating stdout and stderr to a logfile
771   $ exec 3>&1 > logfile 2>&2 2>&1 >&3 3>&-
772
773 # redirect stderr (only) to a file and to orig. stderr:
774   $ command 2>&2 2>stderr
775 # redirect stderr and stdout to separate files and both to orig. stdout:
776   $ command 2>&1 1>&1 2>stderr 1>stdout
777 # redirect stderr and stdout to separate files and stdout to orig. stdout
778 # AND stderr to orig. stderr:
779   $ command 2>&2 1>&1 2>stderr 1>stdout
780
781 # More fun with STDERR ;)
782   $ ./my-script.sh 2> >(grep -v moron >error.log)|process-output >output.log
783   $  echo "Thats STDOUT" >>(sed 's/stdout/another example/' > foobar)
784 -------------------------------------------------------------------------------
785
786 ZMV-Examples (require autoload zmv)
787 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
788 *Note:* '-n' means no execution (just print what would happen). At
789 -------------------------------------------------------------------------------
790 # serially all files (foo.foo > 1.foo, fnord.foo > 2.foo, ..)
791   $ autoload zmv
792   $ ls *
793   1.c  asd.foo  bla.foo  fnord.foo  foo.fnord  foo.foo
794   $ c=1 zmv '*.foo' '$((c++)).foo'
795   $ ls *
796   1.c  1.foo  2.foo  3.foo  4.foo  foo.fnord
797
798 # Rename "file.with.many.dots.txt" by substituting dots (exept for the last
799 # one!) with a space
800   $ touch {1..20}-file.with.many.dots.txt
801   $ zmv '(*.*)(.*)' '${1//./ }$2'
802
803 # Remove the first 4 chars from a filename
804   $ zmv -n '*' '$f[5,-1]' # NOTE: The "5" is NOT a mistake in writing!
805
806 # Rename names of all files under the current Dir to lower case, but keep
807 # dirnames as-is.
808   $ zmv -Qv '(**/)(*)(.D)' '$1${(L)2}'
809
810 # replace all 4th character, which is "1",  with "2" and so on
811   $ autoload -U zmv
812   $ zmv '(???)1(???[1-4].txt)' '${1}2${2}'
813
814 # Remove the first 15 characters from a string
815   $ touch 111111111111111{a-z}
816   $ autoload zmv
817   $ zmv '*' '$f[16,-1]'
818
819 # Replace spaces (any number of them) with a single dash in file names
820   $ autload zmv
821   $ zmv -n '(**/)(* *)' '$1${2//( #-## #| ##)/-}'
822   # or - with Bash
823   $ find . -depth -name '* *' -exec bash -c '
824   > shopt -s extglob
825   > file=$1
826   > dir=${file%/*}
827   > name=${file##*/}
828   > newname=${name//*([ -]) *([ -])/-}
829   > mv -i -- "$file" "$Dir/$newname"' {} {} \;
830
831 # Clean up file names and remove special characters
832   $ autoload zmv
833   $ zmv -n '(**/)(*)' '$1${2//[^A-Za-z0-9._]/_}'
834
835 # Add *.py to a bunch of python scripts in a directory (some of them end
836 # in *.py and give them all a proper extension
837   $ autoload zmv
838   $ zmv -n '(**/)(con*)(#qe,file $REPLY | grep "python script",)' '$1$2.py'
839
840 # lowercase all extensions (i. e. *.JPG) incl. subfolders
841   $ autoload zmv
842   $ zmv '(**/)(*).(#i)jpg' '$1$2.jpg'
843   # Or - without Zsh
844   $ find Dir -name '*.[jJ][pP][gG]' -print | while read f
845   > do
846   >      case $f in
847   >       *.jpg) ;
848   >       *) mv "$f" "${f%.*}.jpg" ;
849   >       esac
850   > done
851
852 # remove leading zeros from file extension
853   $ autoload zmv
854   $ ls
855   filename.001  filename.003  filename.005  filename.007  filename.009
856   filename.002  filename.004  filename.006  filename.008  filename.010
857   $ zmv '(filename.)0##(?*)' '$1$2'
858   $ ls
859   filename.1  filename.10  filename.2  filename.3  filename.4  filename.5 ..
860
861 # renumber files.
862   $ autoload zmv
863   $ ls *
864   foo_10.jpg  foo_2.jpg  foo_3.jpg  foo_4.jpg  foo_5.jpg  foo_6.jpg ..
865   $ zmv -fQ 'foo_(<0->).jpg(.nOn)' 'foo_$(($1 + 1)).jpg'
866   $ ls *
867   foo_10.jpg  foo_11.jpg  foo_3.jpg  foo_4.jpg  foo_5.jpg  ...
868
869 # adding leading zeros to a filename (1.jpg -> 001.jpg, ..
870   $ autoload zmv
871   $ zmv '(<1->).jpg' '${(l:3::0:)1}.jpg'
872
873 # See above, but now only files with a filename >= 30 chars
874   $ autoload zmv
875   $ c=1 zmv "${(l:30-4::?:)}*.foo" '$((c++)).foo'
876
877 # Replace spaces in filenames with a underline
878   $ autoload zmv
879   $ zmv '* *' '$f:gs/ /_'
880
881 # Change the suffix from *.sh to *.pl
882   $ autoload zmv
883   $ zmv -W '*.sh' '*.pl'
884
885 # Add a "".txt" extension to all the files within ${HOME}
886   # ``-.'' is to only rename regular files or symlinks to regular files,
887   # ``D'' is to also rename hidden files (dotfiles))
888   $ autoload zmv
889   $ zmv -Q '/home/**/*(D-.)' '$f.txt'
890   # Or to only rename files that don't have an extension:
891   $ zmv -Q '/home/**/^?*.*(D-.)' '$f.txt'
892
893 # Recursively change filenames with characters ? [ ] / = + < > ; : " , - *
894   $ autoload zmv
895   $ chars='[][?=+<>;",*-]'
896   $ zmv '(**/)(*)' '$1${2//$~chars/%}'
897
898 # Removing single quote from filenames (recursively)
899   $ autoload zmv
900   $ zmv -Q "(**/)(*'*)(D)" "\$1\${2//'/}"
901
902 # When a new file arrives (named file.txt) rename all files in order to
903 # get (e. g. file119.txt becomes file120.txt, file118.txt becomes
904 # file119.txt and so on ending with file.txt becoming file1.txt
905   $ autoload zmv
906   $ zmv -fQ 'file([0-9]##).txt(On)' 'file$(($1 + 1)).txt'
907
908 # lowercase/uppercase all files/directories
909   $ autoload zmv
910   $ zmv '(*)' '${(L)1}' # lowercase
911   $ zmv '(*)' '${(U)1}' # uppercase
912
913 # Remove the suffix *.c from all C-Files
914   $ autoload zmv
915   $ zmv '(*).c' '$1'
916
917 # Uppercase only the first letter of all *.mp3 - files
918   $ autoload zmv
919   $ zmv '([a-z])(*).mp3' '${(C)1}$2.mp3'
920
921 # Copy the target `README' in same directory as each `Makefile'
922   $ autoload zmv
923   $ zmv -C '(**/)Makefile' '${1}README'
924
925 # Removing single quote from filenames (recursively)
926   $ autoload zmv
927   $ zmv -Q "(**/)(*'*)(D)" "\$1\${2//'/}"
928
929 # Rename pic1.jpg, pic2.jpg, .. to pic0001.jpg, pic0002.jpg, ..
930   $ autoload zmv
931   $ zmv 'pic(*).jpg' 'pic${(l:4::0:)1}.jpg'
932   $ zmv '(**/)pic(*).jpg' '$1/pic${(l:4::0:)2}.jpg' # recursively
933 -------------------------------------------------------------------------------
934
935 Module-Examples
936 ~~~~~~~~~~~~~~~
937 Please read zshmodules(1) first!
938
939 zsh/pcre (require zmodload zsh/pcre)
940 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
941
942 -------------------------------------------------------------------------------
943 # Copy files of a certain period (date indicated in the filenames)
944   $ zmodload zsh/pcre
945   $ ls -d -- *(e:'[[ $REPLY -pcre-match pcre-regexp ]]':)
946   # or
947   $ m() { [[ $1 -pcre-match pcre-regexp ]] }
948   $ ls -d -- *(+m)
949 -------------------------------------------------------------------------------
950
951 zsh/clone (require zmodload zsh/clone)
952 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
953 -------------------------------------------------------------------------------
954 # Creates a forked instance of the current shell ($! is set to zero) and
955 # execute ``command'' on /dev/tty8 (for this example).
956   $ zmodload zsh/clone
957   $ clone /dev/tty8 && (($! == 0)) && exec command
958 -------------------------------------------------------------------------------
959
960 zsh/datetime (require zmodload zsh/datetime)
961 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
962 -------------------------------------------------------------------------------
963   $ zmodload zsh/datetime
964   $ alias datereplacement='strftime "%Y-%m-%d" $EPOCHSECONDS'
965   $ export DATE=`datereplacement`
966   $ echo $DATE
967
968 #  strip date from filename
969   $ $ zmodload zsh/datetime
970   $ setopt extendedglob
971   $ touch aaa_bbb_20041212_c.dat eee_fff_20051019_g.dat
972   $ strftime -s pattern \
973     '???_???_<0-%Y%m%d>_?.dat' $((EPOCHSECONDS - 365 * 24 * 60 * 60 / 2))
974   $ print -rl -- $~pattern
975   aaa_bbb_20041212_c.dat
976   $ print -rl -- $pattern
977   ???_???_<0-20050815>_?.dat
978
979 # Search files size == 0, to be based on the file name containing a date
980 # rather than the "last modified" date of the file
981   $ zmodload -i zsh/datetime
982   $ strftime -s file "abc_de_%m%d%Y.dat" $((EPOCHSECONDS - 24 * 60 * 60 ))
983   $ files=(**/$file(N.L0))
984   $ (( $#files > 0 )) && print -rl -- $files | \
985     mailx -s "empty files"  foo@bar.tdl
986 -------------------------------------------------------------------------------
987
988 zsh/stat (require zmodload zsh/stat)
989 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
990 -------------------------------------------------------------------------------
991 # comparing file dates
992   $ zmodload zsh/stat
993   $ file1=foo
994   $ file2=bar
995   $ touch bar & sleep 5 & touch foo
996   $ echo $file1 is $(($(stat +mtime $file2) - \
997     $(stat +mtime $file1))) seconds older than $file2.
998   bar is 5 seconds older than foo
999
1000 # list the files of a disk smaller than some other file
1001   $ zmodload zsh/stat
1002   $ stat -A max +size some-other-file
1003   $ print -rl ./**/*(D.L-$max)
1004
1005 # List the top 100 biggest files in a disk
1006   $ zmodload zsh/stat
1007   $ ls -fld ./**/*(d`stat +device .`OL[1,100])
1008
1009 # Get only the user name and the file names from (like
1010 # ls -l * | awk '{print $3" " $8}')
1011   $ zmodload zsh/stat
1012   $ for file; do
1013   >   stat -sA user +uid -- "$file" &&
1014   >     print -r -- "$user" "$file"
1015   > done
1016
1017 # get the difference between actual bytes of file and allocated bytes of file
1018   $ zmodload zsh/stat
1019   $ print $(($(stat +block -- file) * 512 - $(stat +size -- file)))
1020
1021 # Find largest file
1022 # ``D''  : to include dot files (d lowercase is for device)
1023 # ``O''  : reverse Ordered (o lowercase for non-reverse order)
1024 # ``L''  : by file Length (l is for number of links)
1025 # ``[1]'': return only first one
1026   $ zmodload zsh/stat
1027   $ stat +size ./*(DOL[1])
1028
1029 # file size in bytes
1030   $ zmodload zsh/stat
1031   $ stat -L +size ~/.zshrc
1032   4707
1033
1034 # Delete files in a directory that hasn't been accessed in the last ten days
1035 # and send ONE mail to the owner of the files informing him/her of the files'
1036 # deletion.
1037   $ zmodload zsh/stat zsh/files
1038   $ typeset -A f; f=()
1039   $ rm -f /path/**/*(.a+10e{'stat -sA u +uidr $REPLY; f[$u]="$f[$u]$REPLY"'})
1040   $ for user (${(k)f}) {print -rn $f[$user]|mailx -s "..." $user}
1041
1042 # Get a "ls -l" on all the files in the tree that are younger than a
1043 # specified age
1044   $ zmodload zsh/stat
1045   $ for d (. ./**/*(N/m-2))
1046   >   print -r -- $'\n'$d: && cd $d && {
1047   >      for f (*(Nm-2om))
1048   >   stat -F '%b %d %H:%M' -LsAs -- $f &&
1049   >   print -r -- $s[3] ${(l:4:)s[4]} ${(l:8:)s[5]} \
1050   >   ${(l:8:)s[6]} ${(l:8:)s[8]} $s[10] $f ${s[14]:+-> $s[14]}
1051   >   cd ~-
1052   > }
1053
1054 # get file creation date
1055   $ zmodload zsh/stat
1056   $ stat -F '%d %m %Y' +mtime ~/.zshrc
1057   30 06 2004
1058   $ stat -F '%D' +mtime ~/.zshrc
1059   06/30/04
1060 -------------------------------------------------------------------------------
1061
1062 zsh/files (require zmodload zsh/files)
1063 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1064 -------------------------------------------------------------------------------
1065 # search a directory for files containing a certain string then copy those
1066 # files to another directory.
1067   $ zmodload zsh/files
1068   $ IFS=$'\0'
1069   $ cp $(grep -lZr foobar .) otherdirectory
1070 -------------------------------------------------------------------------------
1071
1072 zsh/mapfile (require zmodload zsh/mapfile)
1073 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1074 -------------------------------------------------------------------------------
1075 # grepping for two patterns
1076   $ zmodload zsh/mapfile
1077   $ pattern1="foo"
1078   $ pattern2="bar foo"
1079   $ print -l ./**/*(DN.e{'z=$mapfile[$REPLY] && [[ $z = *$pattern1* && \
1080     $z = *$pattern2* ]]'})
1081 # or a solution in combination with zsh/pcre
1082   $ zmodload -i zsh/mapfile zsh/pcre
1083   $ pattern1="foo"
1084   $ pattern2="bar foo"
1085   $ pcre_compile "(?s)(?=.*?$pattern1).*?$pattern2"
1086   $ pcre_study
1087   $ print -l ./**/*(DN.e{'pcre_match $mapfile[$REPLY]'})
1088
1089 # equivalent for ``less /etc/passwd | grep -v root''
1090   $ zmodload zsh/mapfile
1091   $ IFS=$'\n\n'
1092   $ print -rl -- ${${=mapfile[/etc/passwd]}:#*root*}
1093 # or - for case insensitive
1094   $ setopt extendedglob
1095   $ print -rl -- ${${=mapfile[/etc/passwd]}:#*(#i)root*}
1096
1097 # If a XML-file contains stuff like ``<TAGA/>'' and ``<TAGB/>'', number
1098 # this empty tags (ones ending in '/>') so if encountered in the same
1099 # order, the preceeding tags would become ``<TAGA/>1</TAGA>'' and
1100 # ``<TAGB/>2</TAGB>''
1101   $ zmodload zsh/mapfile
1102   $ cnt=0
1103   $ apfile[data.xml.new]=${(S)mapfile[data.xml]//\
1104   > (#im)<TAGA>*<\/TAGA>/<TAGA>$((++cnt))<\/TAGA>}
1105
1106 # removing all files in users Maildir/new that contain ``filename="gone.src''
1107   $ zmodload zsh/{files,mapfile}
1108   $ rm -f /u1/??/*/Maildir/new/100*(.e{'[[ $mapfile[$REPLY] == \
1109     *filename=\"gone.scr\"* ]]'})
1110
1111 # Grep out the Title from a postscript file and append that value to the
1112 # end of the filename
1113   $ autoload -U zmv
1114   $ zmodload zsh/mapfile
1115   $ zmv '(*).ps' '$1-${${${mapfile[$f]##*%%Title: }%% *}//[^a-zA-Z0-9_]/}.ps'
1116 -------------------------------------------------------------------------------
1117
1118 zsh/mathfunc (require zmodload zsh/mathfunc)
1119 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1120 -------------------------------------------------------------------------------
1121 $ zmodload zsh/mathfunc
1122 $ echo $(( sin(1/4.0)**2 + cos(1/4.0)**2 - 1 ))
1123   -1.1102230246251565e-16
1124 $ echo $(( pi = 4.0 * atan(1.0) ))
1125   3.1415926535897931
1126 $ echo $(( f = sin(0.3) ))
1127   0.29552020666133955
1128 $ print $((1e12 * rand48()))
1129   847909677310.23413
1130 $ print $(( rand48(seed) ))
1131   0.01043488334700271
1132 -------------------------------------------------------------------------------
1133
1134 zsh/termcap (require zmodload zsh/termcap)
1135 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1136 -------------------------------------------------------------------------------
1137  $ zmodload -ab zsh/termcap echotc
1138  $ GREEN=`echotc AF 2`
1139  $ YELLOW=`echotc AF 3`
1140  $ RED=`echotc AF 1`
1141  $ BRIGHTRED=`echotc md ; echotc AF 1`
1142  $ print -l ${GREEN}green ${YELLOW}yellow ${RED}red ${BRIGHTRED}brightred
1143 -------------------------------------------------------------------------------
1144
1145 zsh/zpty (require zmodload zsh/zpty)
1146 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1147 -------------------------------------------------------------------------------
1148   $ zmodload zsh/zpty
1149   $ zpty PW passwd $1
1150   $ zpty PW passwd $1
1151 # ``-r'': read the output of the command name.
1152 # ``z'' : Parameter
1153   $ zpty -r PW z '*password:'
1154 # send the to command name the given strings as input
1155   $ zpty -w PW $2
1156   $ zpty -r PW z '*password:'
1157   $ zpty -w PW $2
1158 # The second form, with the -d option, is used to delete commands
1159 # previously started, by supplying a list of their names. If no names
1160 # are given, all commands are deleted. Deleting a command causes the HUP
1161 # signal to be sent to the corresponding process.
1162   $ zpty -d PW
1163 -------------------------------------------------------------------------------
1164
1165 zsh/net/socket (require zmodload zsh/net/socket)
1166 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1167 -------------------------------------------------------------------------------
1168 # ``-l'': open a socket listening on filename
1169 # ``-d'': argument will be taken as the target file descriptor for the
1170 #         connection
1171 # ``3'' : file descriptor. See ``A User's Guide to the Z-Shell''
1172 #         (3.7.2: File descriptors)
1173   $ zmodload zsh/net/socket
1174   $ zsocket -l -d 3
1175 # ``-a'': accept an incoming connection to the socket
1176   $ zsocket -a -d 4 3
1177   $ zsocket -a -d 5 3 # accept a connection
1178   $ echo foobar >&4
1179   $ echo barfoo >&5
1180   $ 4>&- 5>&- 3>&
1181 -------------------------------------------------------------------------------
1182
1183 zsh/zftp (require zmodload zsh/zftp)
1184 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1185 -------------------------------------------------------------------------------
1186  $ autoload -U zfinit
1187  $ zfinit
1188  $ zfparams www.example.invalid myuserid mypassword
1189  $ zfopen
1190  $ zfcd tips
1191  $ zfls -l zshtips.html
1192  $ zfput zshtips.html
1193  $ zfls -l zshtips.html
1194
1195 # Automatically transfer files using FTP with error checking
1196   $ autoload -U zfinit ; zfinit
1197   $ zftp open host.name.invalid user passwd || exit
1198   $ zftp get /remote/file > /local/file; r=$?
1199   $ zftp close && exit r
1200
1201 # compress and ftp on the fly
1202   $ autoload -U zfinit ; zfinit
1203   $ zftp open host.name.invalid user password
1204   $ zftp get $file | bzip2 > ${file}.bz2
1205   $ zftp close
1206
1207 # Recursice ``get''
1208   $ autoload -U zfinit ; zfinit
1209   $ zfanon cr.yp.to
1210   $ zfcd daemontools
1211   $ for file in `zfls` ; do
1212   >     zfget $file
1213   $ done
1214   $ zfclose
1215
1216 # Upload all regular files in $HOME/foobar (recursive) that are newer than
1217 # two hours to ftp.foobar.invalid/path/to/upload
1218   $ autoload -U zfinit ; zfinit
1219   $ zfopen ftp.foobar.invalid/path/to/upload
1220   $ cd $HOME/foobar
1221   $ zfput -r **/*(.mh-2)
1222   $ zfclose
1223
1224 # long list of files on a ftp
1225   $ autoload -U zfinit ; zfinit
1226   $ zfopen some-host
1227   $ zfcd /some/remote/Dir
1228   $ cd /some/local/Dir
1229 # If the list.txt is located on the remote host, change to
1230 # zfget ${(f)"$(zftp get /path/to/remote/list.txt)"}
1231   $ zfget ${(f)"$(cat list.txt)"}
1232   $ zfclose
1233 -------------------------------------------------------------------------------
1234
1235 zsh/zselect (require zmodload zsh/zselect)
1236 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
1237 -------------------------------------------------------------------------------
1238 # It's similar to
1239  ,----
1240  | $ sg=$(stty -g)
1241  | $ stty -icanon min 0 time 50
1242  | $ read yesno
1243  | $ stty "$sg"
1244  | $ case "$yesno" in
1245  | >  yes) command1;;
1246  | >  *) command2;;
1247  | > esac
1248  `----
1249 $ zmodload zsh/zselect
1250 $ if zselect -t 500 -r 0 && read yesno && [ yes = "$yesno" ]; then
1251 >    command1
1252 > else
1253 >    command1
1254 > fi
1255 ------------------------------------------------------------------------------
1256
1257 OPTIONS
1258 -------
1259 Navigation options
1260 ~~~~~~~~~~~~~~~~~~
1261 *auto_cd* (allow one to change to a directory by entering it as a
1262 command). *auto_pushd* (automatically append dirs to the push/pop list)
1263 pushd_ignore_dups (and don't duplicate them).
1264
1265 Misc
1266 ~~~~
1267 *no_hup* (don't send  HUP signal to background jobs when exiting ZSH).
1268 *print_exit_value* (show a message with the exit code when a command
1269 returns with a non-zero exit code)
1270
1271 History options
1272 ^^^^^^^^^^^^^^^
1273 *hist_verify* (let the user edit the command line after history
1274 expansion (e.g. !ls) instead of immediately running it) +
1275 Use the same history file for all sessions : +
1276 *setopt SHARE_HISTORY*
1277
1278 Privacy / Security
1279 ^^^^^^^^^^^^^^^^^^
1280 *no_clobber*  (or set -C; prevent '>' redirection from truncating
1281 the given file if it already exists)
1282
1283 Spelling correction
1284 ^^^^^^^^^^^^^^^^^^^
1285 *correct* (automatically correct the spelling of commands).
1286 *correct_all* (automatically correct the spelling of each word on the
1287 command line) *dvorak* (dvorak layout)
1288
1289 UNSORTED/MISC
1290 -------------
1291 Mailpath: simple multiple mailpath:
1292 -----------------------------------------------------
1293 mailpath=($HOME/Mail/mbox'?new mail in mbox'
1294           $HOME/Mail/tux.u-strasbg'?new mail in tux'
1295           $HOME/Mail/lilo'?new mail in lilo'
1296           $HOME/Mail/ldap-fr'?new mail in ldap-fr')
1297 -----------------------------------------------------
1298
1299 Mailpath: dynamic mailpath:
1300 -----------------------------------------------------
1301 typeset -a mailpath
1302 for i in ~/Mail/Lists/*(.); do
1303    mailpath[$#mailpath+1]="${i}?You have new mail in ${i:t}."
1304 done
1305 -----------------------------------------------------
1306 Avoid globbing on special commands:
1307 --------------------------------------------------------
1308 for com in alias expr find mattrib mcopy mdir mdel which;
1309 alias $com="noglob $com"
1310 --------------------------------------------------------
1311
1312 For migrating your bashprompt to zsh use the script bash2zshprompt located in
1313 the zsh source distribution under 'Misc'.
1314
1315 For migration from (t)csh to zsh use the c2z tool that converts csh
1316 aliases and environment and shell variables to zsh. It does this by running
1317 csh, and having csh report on aliases and variables. The script then converts
1318 these to zsh startup files. It has some issues and usage information that are
1319 documented at the top of this script.
1320
1321 Here are functions to set the title and hardstatus of an *XTerm* or of *GNU
1322 Screen* to 'zsh' and the current directory, respectively, when the prompt is
1323 displayed, and to the command name and rest of the command line, respectively,
1324 when a command is executed:
1325 ------------------------------------------------------------------
1326 function title {
1327       if [[ $TERM == "screen" ]]; then
1328         # Use these two for GNU Screen:
1329         print -nR $' 33k'$1$' 33'\
1330         print -nR $' 33]0;'$2$''
1331       elif [[ $TERM == "xterm" || $TERM == "rxvt" ]]; then
1332         # Use this one instead for XTerms:
1333         print -nR $' 33]0;'$*$''
1334       fi
1335 }
1336 function precmd { title zsh "$PWD" }
1337 function preexec {
1338     emulate -L zsh
1339     local -a cmd; cmd=(${(z)1})
1340     title $cmd[1]:t "$cmd[2,-1]"
1341 }
1342 ------------------------------------------------------------------
1343
1344 Put the following line into your ~/.screenrc to see this fancy hardstatus:
1345 -----------------------------------------
1346 caption always "%3n %t%? (%u)%?%?: %h%?"
1347 -----------------------------------------
1348
1349
1350 Special variables which are assigned:
1351 ------------------------------------------------------
1352 $LINENO $RANDOM $SECONDS $COLUMNS $HISTCHARS $UID
1353 $EUID $GID $EGID $USERNAME $fignore $mailpath $cdpath
1354 ------------------------------------------------------
1355
1356 LINKS
1357 -----
1358 Primary site::
1359   *http://www.zsh.org/[]*
1360 Project-page::
1361   *http://sourceforge.net/projects/zsh/[]*
1362 Z shell page at sunsite.dk::
1363     *http://zsh.sunsite.dk/[]*
1364 From Bash to Z Shell: Conquering the Command Line - the book::
1365     *http://www.bash2zsh.com/[]*
1366 Mailinglistarchive::
1367     *http://www.zsh.org/mla/[]*
1368 ZSH-FAQ::
1369     *http://www.zsh.org/FAQ/[]*
1370 Userguide::
1371     *http://zsh.sunsite.dk/Guide/[]*
1372 ZSH-Wiki::
1373     *http://www.zshwiki.org/[]*
1374 Die Zsh als interaktive Shell::
1375     *http://cssun.rrze.uni-erlangen.de/~sipakale/zshreferat.html[]*
1376 A short introduction from BYU::
1377     *http://docs.cs.byu.edu/docs/zsh/index.php[]*
1378 Mouse-Support ;)::
1379     *http://stchaz.free.fr/mouse.zsh[]*
1380 Shell Corner: Zsh Suite of "keeper" Functions::
1381     *http://www.unixreview.com/documents/s=9513/ur0501a/ur0501a.htm[]*
1382 The Z Shell (A Fan Page)::
1383     *http://www.princeton.edu/~kmccarty/zsh.html[]*
1384 Making the Transition to Zsh::
1385     *http://www.linux-mag.com/cgi-bin/printer.pl?issue=2002-05&article=power[]*
1386 Curtains up: introducing the Z shell::
1387     *http://www-128.ibm.com/developerworks/linux/library/l-z.html?dwzone=linux[]*
1388 ZSH-Liebhaberseite::
1389     *http://michael-prokop.at/computer/tools_zsh_liebhaber.html[]*
1390 ZSH-Seite von Michael Prokop::
1391     *http://www.michael-prokop.at/computer/tools_zsh.html[]*
1392 A Case for the Z Shell on *http://www.daemonnews.org/[]*::
1393     *http://ezine.daemonnews.org/199910/zsh.html[]*
1394 ZSH-Section from Dotfiles.com::
1395     *http://www.dotfiles.com/index.php?app_id=4[]*
1396 Writing Zsh Completion Functions::
1397     *http://www.linux-mag.com/2002-07/power_01.html[]*
1398 ZSH Prompt introduction::
1399     *http://aperiodic.net/phil/prompt/[]*
1400 Adam's ZSH page::
1401     *http://www.adamspiers.org/computing/zsh/[]*
1402 Zzappers Best of ZSH Tips::
1403     *http://www.rayninfo.co.uk/tips/zshtips.html[]*
1404 Zsh Webpage by Christian Schneider::
1405     *http://strcat.de/wiki/zsh/[]*
1406     *http://strcat.de/wiki/zsh-german[]* (German translation. Help needed!)
1407 The zsh-lovers webpage::
1408     *http://grml.org/zsh/[]*
1409 IRC channel::
1410     *#zsh at irc.freenode.org*
1411 The Z shell reference-card (included in the zsh-lovers debian-package)::
1412     *http://www.bash2zsh.com/zsh_refcard/refcard.pdf[]*
1413
1414 AUTHORS
1415 -------
1416 This manpage was written by Michael Prokop, Christian 'strcat'
1417 Schneider and Matthias Kopfermann. But many ideas have been taken from
1418 zsh-geeks e.g. from the zsh-mailinglists (zsh-users and zsh-workers),
1419 google, newsgroups and the zsh-Wiki. +
1420 Thanks for your cool and incredible tips. We learned much from you!
1421
1422 In alphabetic order:
1423 -------------------------------------------------------------------------
1424 Andrew 'zefram' Main  - http://www.fysh.org/~zefram/
1425 Barton E. Schaefer    - http://www.well.com/user/barts/
1426 Matthias Kopfermann   - http://www.infodrom.north.de/~matthi/
1427 Oliver Kiddle         - http://people.freenet.de/opk/
1428 Paul Falstad          - http://www.falstad.com/
1429 Peter Stephenson      - http://homepage.ntlworld.com/p.w.stephenson/
1430 Richard Coleman
1431 Stephane Chazelas     - http://stephane.chazelas.free.fr/
1432 Sven Guckes           - http://www.guckes.net/
1433 Sven Wischnowsky      - http://w9y.de/zsh/zshrc
1434 -------------------------------------------------------------------------
1435
1436 SEE ALSO
1437 --------
1438 Manpages of zsh:
1439 ------------------------------------------------------------------
1440        zsh          Zsh overview
1441        zshall       Tthe Z shell meta-man page
1442        zshbuiltins  Zsh built-in commands
1443        zshcompctl   Zsh completion control
1444        zshcompsys   Zsh completion system
1445        zshcompwid   Zsh completion widgets
1446        zshcontrib   User contributions to zsh
1447        zshexpn      Zsh expansion and substitution
1448        zshmisc      Anything not fitting into the other sections
1449        zshmodules   Zsh loadable modules
1450        zshoptions   Zsh options
1451        zshparam     Zsh parameters
1452        zshroadmap   Informal introduction to the zsh manual
1453        zshtcpsys    Zsh tcp system
1454        zshzle       Zsh command line editing
1455        zshzftpsys   Zsh built-in FTP client
1456        zshall       Meta-man page containing all of the above
1457 ------------------------------------------------------------------
1458
1459 Note: especially 'man zshcontrib' covers very useful topics! +
1460 Book: *From Bash to Z Shell* by Oliver Kiddle, Jerry Peck and Peter
1461 Stephenson. *ISBN: 1590593766*. - *http://www.bash2zsh.com/[bash2zsh.com]* +
1462 Also take a look at the section *LINKS* in this manpage.
1463
1464 BUGS
1465 ----
1466 Probably. This manpage might be never complete. So please report bugs,
1467 feedback and suggestions to <zsh-lovers@michael-prokop.at>. Thank
1468 you!
1469
1470 COPYRIGHT
1471 ---------
1472 Copyright  \(C) Michael Prokop, Christian Schneider and Matthias
1473 Kopfermann.
1474
1475 // vim:tw=80 ai