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