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