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