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