1 .\" Title: zsh-lovers, 1
2 .\" Author: Michael Prokop / www.michael-prokop.at / www.grml.org
3 .\" Latest change: Son Jun 19 12:13:40 CEST 2005 [mika]
4 .\"###############################################################
6 .\"###############################################################
7 .TH zsh\-lovers 1 "2005-06-19" "zsh 4\&.2\&.5"
9 zsh\-lovers \- tips, tricks and examples for the Z shell
11 Whenever we look at the zsh manual we wonder why there are no examples
12 for those simply things in (shell) life. The zsh contains many features,
13 but there was no manpage with some examples (like procmailex(5)).
14 That's why we wrote this manpage.
16 Most of the tricks and oneliner come from the mailinglists
17 zsh\-users, zsh\-workers, google, newsgroups and from ourself.
23 This manpage (zsh-lovers(1)) is
25 an offical part of the Z shell! It's just a just for fun \- manpage ;)
26 For comments, bugreports and feedback take a quick look at the section
28 .\"#######################################################
30 .\"#######################################################
34 See also \fIman 1 zshmisc\fP\&.
36 null command shorthands:
38 "< file" is like "$READNULLCMD <file"
39 "> file" is like "cat >file"
40 ">> file" is like "cat >>file"
44 Append `exit 1' at the end of all *.sh \- files:
46 $ echo "exit 1" >> *.sh
50 Append /etc/services at the end of file `foo' and `bar':
52 $ cat /etc/services >> foo >> bar
58 $ echo An error >&2 2>&1 | sed -e 's/A/I/'
60 .\"#######################################################
62 .\"#######################################################
64 MULTIPLE I/O REDIRECTION
65 Requires \fIsetopt multios\fP! Some examples:
68 Print output of 'ls' into files 'foo' and 'bar':
74 Send standard output of one process to standard input of
75 several processes in the pipeline:
77 $ process1 > >(process1) > >(process2)
81 Redirection to file as well as send on to pipe:
83 $ make install > /tmp/logfile | grep -i error
87 Redirect stderr to a command like xless without redirecting
91 \&.\&.\&. but this executes the command asynchronously. To do it synchronously:
93 $ { { foo 1>&3 } 2>&1 | xless } 3>&1
97 Redirect stderr two times:
99 $ setopt multios ; program 2> file2 > file1 2>&1
103 More fun with stderr:
105 $ ./my-script.sh 2> >(grep -v geek >error.log) | process-output > output.log
106 echo "Thats STDOUT" >>(sed 's/stdout/another example/' > foobar)
108 .\"#######################################################
110 .\"#######################################################
113 Modifiers are a powerful mechanism that lets you modify the results returned by
114 parameter, filename and history expansion. See zshexpn(1) for details.
116 Remove a trailing pathname component, leaving the head. This works like `dirname':
122 Remove all leading pathname components, leaving the tail. This works like `basename'.
128 Remove a filename extension of the form `.xxx', leaving the root name.
136 Remove all but the extension.
145 Print the new command but do not execute it. Only works with history expansion.
153 Quote the substituted words, escaping further substitutions.
162 Convert the words to all lowercase.
171 Convert the words to all uppercase.
180 Variables can be modified by modifiers, too. That makes modification of
181 variables possible without using any external program.
183 sentence="beginning and some words of a sentence with end."
186 Now lets split this sentence-var by using the (s| |) modifier which modifies
187 words by splitting at " ":
189 words=${(s| |)sentence}
190 print $words[1] -> "beginning"
191 print $words[-1] ->"end."
194 Now if one wants to have the beginning of a sentence with a Capital, it's as
197 print "${(C)words[1]} $words[2,-1]"
200 which capitalizes the first word of the list words and then adds with " "
201 second to last word of words. It's possible to join these words as a colon
204 colonlist=${(j|,|)words} # (j|,|) joins with ",".
207 You can see that it's a scalar by testing with (t):
209 print ${(t)colonlist} prints "scalar".
210 print ${(t)words} prints "array".
213 It's possible to sort arrays with o and O:
215 print ${(o)words} # lists the words-array sorted (forwards)
216 print ${(O)words} # lists the words-array sorted (backwards)
218 .\"#######################################################
221 .\"#######################################################
223 See also \fIman 1 zshcompctl zshcompsys zshcompwid\fP\&.
224 zshcompctl is the old style of zsh programmable completion,
225 zshcompsys is the new completion system, zshcompwid are the
226 zsh completion widgets.
228 Some functions, like _apt and _dpkg, are very slow. You can
229 use a cache in order to proxy the list of results (like the
230 list of available debian packages) Use a cache:
232 zstyle ':completion:*' use-cache on
233 zstyle ':completion:*' cache-path ~/.zsh/cache
236 Prevent CVS files/directories from being completed :
238 zstyle ':completion:*:(all-|)files' ignored-patterns '(|*/)CVS'
239 zstyle ':completion:*:cd:*' ignored-patterns '(*/)#CVS'
243 Fuzzy matching of completions for when you mistype them:
245 zstyle ':completion:*' completer _complete _match _approximate
246 zstyle ':completion:*:match:*' original only
247 zstyle ':completion:*:approximate:*' max-errors 1 numeric
251 And if you want the number of errors allowed by _approximate
252 to increase with the length of what you have typed so far:
254 zstyle -e ':completion:*:approximate:*' max-errors 'reply=( $(( ($#PREFIX+$#SUFFIX)/3 )) numeric )'
258 Ignore completion functions for commands you don't have:
260 zstyle ':completion:*:functions' ignored-patterns '_*'
264 With helper functions like:
266 xdvi() { command xdvi ${*:-*.dvi(om[1])} }
269 you can avoid having to complete at all in many
270 cases, but if you do, you might want to fall into menu
271 selection immediately and to have the words sorted by time:
273 zstyle ':completion:*:*:xdvi:*' menu yes select
274 zstyle ':completion:*:*:xdvi:*' file-sort time
278 Completing process IDs with menu selection:
280 zstyle ':completion:*:*:kill:*' menu yes select
281 zstyle ':completion:*:kill:*' force-list always
285 If you end up using a directory as argument, this will
286 remove the trailing slash (usefull in ln)
288 zstyle ':completion:*' squeeze-slashes true
292 cd will never select the parent directory (e.g.: cd ../<TAB>):
294 zstyle ':completion:*:cd:*' ignore-parents parent pwd
296 .\"#######################################################
298 .\"#######################################################
299 .SS "ADVANCED GLOBBING"
300 See \fIman zshexpn | less -p 'Glob Qualifiers'\fP
303 List file 'foobar' via recursiv search in directories:
309 List files file20, file30, file100, etc:
315 List files with suffix c and pro (e.g. foo.c, bar.pro):
316 .\" Anmerkung: es gibt da ein noch genaueres Pattern - FIXME
322 List files which are word-readable:
328 List all .c-files except 'lex.c':
334 List all `README' - files case-insensitive with max. one typo
335 (e.g. RADME, REEME, RAEDME):
341 List files named README but accept one spelling error including
342 case-insensitive (e.g. RADME, REEME, RAEDME):
348 List executable files, directories and symlinks:
354 List dangling symlinks:
360 List all zero-length-files which are not group- or
367 .\"List the last two modified files/directories:
368 .\" FIXME - stimmt das?
374 .\"Edit newest file with vim:
375 .\" FIXME - stimmt das?
377 .\" $ vim *(.om[1]^D)
381 List all .c-files for which there doesn't exist a .o file:
383 $ c=(*.c) o=(*.o(N)) eval 'ls ${${c:#(${~${(j:|:)${o:r}}}).c}:?done}'
387 Find (and print) all symbolic links without a target within
390 $ file **/*(D@) | fgrep broken
391 $ for i in **/*(D@); [[ -f $i || -d $i ]] || echo $i
392 $ echo **/*(@-^./=%p)
397 Rename all MP3-files from name with spaces.mp3 to Name With
401 mv $i ${${(C)i}:s/Mp3/mp3/}
406 Rename all PDF-files from name.mp3 to Name.mp3 (lowercase to
407 uppercase of first letter) without touching the rest of the
410 $ zmv '([a-z])(*).pdf' '${(C)1}$2.pdf'
414 Substitutions in strings can be done by string-indexes:
416 $ a="doh.";a[1]='d';a[-1]='. (Bart Simpson)'
424 $ typeset -A ass_array; ass_array=(one 1 two 2 three 3 four 4)
425 $ print ${(k)ass_array} # prints keys
427 $ print ${(v)ass_array} # prints values
429 $ print $ass_array[one]
434 Extract parts of a string. Print first word of output of 'date':
436 $ print ${$( date )[1]}
440 Extract parts of a string. Print ip-address of loopback device:
442 $ print ${${$( LC_ALL=C /sbin/ifconfig lo )[6]}#addr:}
446 Print specific line of a file. E.g. print line 5 of file:
448 $ print -l ${"$( < file )"[(f)5]}
452 Print line containing string 'root' of file /etc/passwd:
454 $ print ${"$( < /etc/passwd )"[(fr)*root*]}
458 .\" print -l ${(M)${(f)"$(< /etc/passwd)"##*$muster*}} (f)
459 .\" liest die in Anführungsstrichen stehende Ausgabe der Datei zeilenweise in eine unbenannte Variable. Wie auch in anderen Shells schneidet ## am Anfang *$muster* ab.
460 .\" Da aber (M) benutzt wird, werden alle Zeilen, bei denen das Muster zutrifft, nicht abgeschnitten, sondern alleine ausgegeben. Das Gegenstück dazu ist (R), was im vorigen Fall dann einem "grep -v" entspricht.
461 .\" Würde man nur ein # angeben, würden die Sterne (Stellvertreter für 0 oder mehr Zeichen) geizig - mit so wenig Zeichen wie möglich - ausgegeben. In diesem Fall würde dann also nur $muster selber ausgeben.
462 .\" Zsh kann wie bekanntere Programmiersprachen (Perl, Python, Ruby z.B) im Index einer Variablen ein "von_feld,bis_feld".
465 Print words two to four of output of 'date':
467 $ print ${$( date )[2,4]}
473 .\" $ print ${${:-one two three four five}[2,-2]}
476 .\"gibt als Ergebnis zwei drei vier aus. (':-' ersetzt den
477 .\"fehlenden Variablennamen hier wie bei der Bash durch seine
481 Use of two-dimensional indizes. Print time via date but
484 $ print ${$(date)[4][1,5]}
488 .\" Mit dem sogenannten Here-String kann man eine Art Here-Document benutzen ohne ein EOT-Signal auf einer Extra-Zeile eingeben zu müssen:
490 .\" for Programm in cat tail head grep ; do >> /tmp/datei \
491 .\" <<< "Hallo,Welt! Ich habe das Geüfhl, mein \
492 .\" externes $Programm wird bald nicht mehr so viel benutzt." ; done
493 .\" Man achte auch auf das Auslassen von cat, was bei der zsh nicht mehr nötig ist!
496 Calculate floating point numbers:
498 $ printf "%.0f\n" $[ 2.8*15 ]
501 .\" Ausserdem kann in verschiedenen Zahlensystemen gerechnet werden, in dem in eckigen Klammern [#<zahlensystem>] geschrieben wird, also:
503 .\" for (( i=1; i<100; i++ )) { print $(( [#10] i)) }
507 .\" Bei zweifacher Angabe von # wird das Zahlensystem nicht ausgegeben.
509 .\" Sogar einen "Taschenrechner" gibt es in der Zsh, der nach autoload zcalc zur Verfügung steht.
511 .\" Beispiele zur Vervollständigung (noch nach dem alten Schema bis 3.1.5):
513 .\" compctl -g '*(/)' cd
514 .\" macht aus einer einfachen Dateiergänzung wie der Ksh eine intelligente Vervollständigung für "cd", die nur noch Verzeichnisnamen aufführt.
515 .\" Vor allem mit compctl -k '(`aktion`)' lassen sich sehr praktische Vervollständigungsmechanismen erstellen. Man kann sich so z.B. ohne Probleme bei Aufruf eines Email-Programmes nur Email-Adressen und mit ftp nur FTP-Adressen vervollständigen lassen. Außerdem kann man bei der Vervollständigung auch Dateienden abschneiden lassen. Das ist z.B. bei Java sehr praktisch.
517 .\" compctl -g '*.class(:r)' java
518 .\" (Mehr Beispiele zur älteren Vervollständigung hier)
519 .\" Mit der Zsh kann man sehr gezielt nach Worten in Dateien suchen: Nach dem Freischalten von Sonderzeichen für die Reichweite eines glob-Befehls mit setopt extended_glob ist folgendes machbar:
521 .\" grep Wort *~(*.gz|*.bz|*.bz2|*.zip|*.Z)
522 .\" sucht 'Wort' nicht mehr in den komprimierten Dateien im Mail-Ordner.
523 .\" ~ bedeutet hier so viel wie "außer".
524 .\" Alle Dateien, die nicht die Endung *.bz2 und auch nicht *.gz enthalten , sucht man mit
527 .\" Das ^ ist also das "NICHT", das Ausrufezeichen wird von der Zsh für alte Befehle benutzt.
528 .\" An dieser Stelle bietet sich vielleicht ein globales Alias für komprimierte Dateien an (siehe weiter unten).
529 .\" Zusätzlich zu ^ und ~ lassen sich die Ausdrücke # und ##benutzen, um null und mehr bzw. ein und mehr Vorkommen des Zeichens davor zu erhalten, was bei Perls regulären Ausdrücken den Zeichen * bzw. + entspricht.
530 .\" Globale Aliase sind Aliase, die nicht nur am Anfang der Kommandozeile oder nach ; als Aliase wirken können. Sie sollten gut gekennzeichnet werden:
532 .\" alias -g §k="*~(*.bz2|*.gz|*.tgz|*.zip|*.z)"
533 .\" und danach der Befehl
536 .\" listet alle nicht-komprimierte Dateien auf.
537 .\" Mit unalias '§k' wird man dieses globale Alias wieder los. Wichtig hierbei sind die einfachen Anführungsstriche. Sonst wirkt nämlich §k weiter, was nicht im Sinne des Benutzers wäre.
538 .\" Aliase können seit Version 4.2 auch verwendet werden, um bestimmten Zeichenketten-Endungen (Suffixes) nach einem Punkt automatisch mit dem selben Befehl aufzurufen, was meist für Dateiendungen benutzt wird. Dabei gilt:
541 .\" alias -s NAME=WERT
542 .\" wobei TEXT.NAME dann durch die Zsh zu WERT TEXT.NAME wird.
544 .\" alias -s txt='less -rE'
545 .\" ruft alle ohne Befehl aufgerufenen .txt-Dateien automatisch mit dem Befehl less -rE auf, so dass man jetzt einfach nur den Dateinamen und ein return eingeben muss. Diese Funktionalität ist vergleichbar mit dem Anklicken einer oder mehrerer Dateien mit einem graphischen Dateimanager. Dabei kann man auch globale Zeichen wie * verwenden, also beispielsweise *.txt und ein "enter" eingeben um alle Dateien mit Endung ".txt" mit less zu lesen.
546 .\" Praktischerweise gibt es mit autoload zsh-mime-setup ; zsh-mime-setup die Möglichkeit, anhand der Mime-Definitionen in /etc/ schon bestimmte Datei-Endungen mit bestimmten Programmen zu belegen.
551 .\" ruft alle WWW-Seiten mit .de oder .at direkt mit w3m auf. ('.de' bzw. '.at' in der Eingabe ist in diesem Fall keine Dateiendung!)
552 .\" In der Zsh kann man aus jeder eigenen Funktion eine Datei machen, ohne dass diese Datei ausführbar sein muss. Hierzu setzt man die Variable FPATH bzw fpath (siehe unten) auf das oder die Verzeichnisse, die berücksichtigt werden sollen.
553 .\" In der Datei genügt es, einfach eine oder mehrere Funktionen zu schreiben, z.B:
555 .\" begruessung() { echo "Hallo, $1" ; }
556 .\" herzlich() { echo "Ist ja riesig, $1, Dich zu sehen" ; }
557 .\" Jetzt muss noch dieser Dateiname mit autoload dateiname bekannt gemacht werden. Daraufhin stehen nach einmaligem Aufruf des Namens der Funktionen die beiden Funktionen dann zur Verfügung. Schreibt man nur den Funktionsrumpf allein dann hat das gegenüber dem Schreiben von Funktionen den Vorteil, sofort ausgeführt werden zu können. autoload-Funktionen müssen nämlich erst einmal aufgerufen werden, damit ihr Rumpf bekannt ist. Beispiel:
559 .\" echo "Ist das schön, $1, Dich zu sehen\!" > ~/.zsh/funktionen/begruessung
560 .\" ist nach Aufruf von autoload begruessung sofort nutzbar. (Siehe AUTOLOADING FUNCTIONS unter 'man zshmisc')
561 .\" Statt in eine "Backslashitis" beim Aufschreiben von Skalar-Variablen mit viel Inhalt zu verfallen (z.B. beim Definieren des Pfades) gibt es bei der Zsh die Möglichkeit, das kleinbuchstabige Gegenüber des großbuchstabigen Variablennamens als eines Arrays zu verwenden und sogar für eigene Variablen mit typeset -T ein "Gegenüber" von einer Skalar-Variable zu einer Feld-Variable durch die Kleinschreibweise der Variablen zu erzielen.
562 .\" Dieser Variante kann man dann ein Feld aus Werten - durch Leerzeichen oder Zeilenumbruch getrennt - zuweisen. Beispiel PATH:
564 .\" alt: PATH=/usr/bin\
565 .\" :/usr/local/bin/\
567 .\" :/usr/local/sbin\
570 .\" zsh: path=( /usr/bin /usr/local/bin /usr/sbin /usr/local/sbin /usr/X11R6/bin )
571 .\" Da die Zsh für Feldvariablen runde Klammern braucht (wenn nicht setopt shwordsplit gesetzt ist) sind die Worte in runde Klammern eingeschlossen.
572 .\" Wer allerdings kompatibel zur Sh/Ksh/Bash programmieren muss/will, der muss die Option setopt shwordsplit setzen.
573 .\" Zle - der Zeileneditor der Zsh - ist den Zeileneditoren anderer Shells überlegen. Hier kann man fröhlich mehrere Zeilen schreiben und nach dem Aufruf mit RETURN separat einzelne Zeilen korrigieren. Man muss also nicht mehr immer einen externen Editor aufrufen.
574 .\" Besonders nett dabei: Wo die Bash nur das Manövrieren wie in einer einzigen Zeile zulässt, kann man bei der Zsh bequem mit dem Cursor - wie in einem Editor - über mehrere Zeilen navigieren.
575 .\" Will man innerhalb mehrerer Zeilen editieren, dann muss man entweder mit bindkey "^Xp" push-line-or-edit oder ähnlicher Tastenbelegung diesen Puffer in einen anderen Puffer kopieren oder aber nach einem Control-C erneut die Zeilen zurückholen.
576 .\" Mittels zle -N kann man eigene, sogenannte Widgets (das sind Editier-Funktionen) zle bekannt machen. In den Variablen LBUFFER und RBUFFER liegt die Kommandozeile links bzw. rechts des Cursors, die man so sehr einfach manipulieren kann. Beispiel:
578 .\" klammer() { LBUFFER="\${$LBUFFER" ; RBUFFER="}$RBUFFER" }
579 .\" erzeugt eine Funktion klammer, die man mit bindkey '^g' klammer jetzt an die Taste Control-G zuweisen kann.
580 .\" Noch ein Beispiel für ein User-Widget:
584 .\" print -n "Wohin? "
588 .\" Jetzt muss mit 'zle -N ' "wohin" als User-Widget deklariert werden. Anschließend kann mit 'bindkey '^Ww' wohin' die definierte und deklarierte Editier-Funktion auf 'Control-Ww' gelegt werden.
589 .\" Zusätzlich kann man mit 'autoload zed' sogar einen Editor (der in der Z Shell selber geschrieben ist) benutzen, der dann von seiner Voreinstellung oder durch 'bindkey -e' Emacs-artig, bei Eingabe von 'bindkey -v' vi-artig funktioniert. Gesichert wird allerdings durch 'control-x control-w' oder im Vicmd-Modus mit 'ZZ' und mit dem Befehl control-c bricht man ab. Ruft man zed mit der Option -f oder als fned auf, kann man Funktionen editieren.
590 .\" Als wohltuend empfinden wir bei einem Kommando des Zeileneditors das Kommando insert-last-word, das im Gegensatz zur Bash nicht immer das letzte Wort, sondern bei wiederholtem Aufruf das letzte Wort davor und so weiter aufruft. (Siehe auch 'man zshzle')
591 .\" Die Zsh unterstützt wie ihr Vorbild -die Ksh- Koprozesse. Koprozesse sind eine Möglichkeit, an Parallelprozesse Daten zu übergeben und Daten zu empfangen. Diese Koprozesse werden allerdings mit 'coproc' eingeleitet und nicht wie bei der Ksh mit |& .
592 .\" Mit ' print -p' und mit '>&p ' als Umlenkung kann ich Daten an den Prozeß senden und mit 'read -p und '<&p' als Umlenkung Daten von diesem Prozeß auslesen. Beispiel:
594 .\" coproc ed /tmp/notizen
598 .\" schreibt in einen parallel laufenden Koprozess, den altehrwürdigen Ed, die Ausgabe von 'ls -l' und speichert den Inhalt in der Datei /tmp/notizen ab und beendet ed.
599 .\" Weitgehender als ein Coprozess ist das Laden des zpty-Moduls mit 'zmodload zsh/zpty', welches dann ähnliche Steuerungsmöglichkeiten wie das Programm expect bietet. Als Beispiel für die Verwendung von zpty kann das Skript nslookup in /usr/share/zsh/4.x.x/functions/ dienen, was das gleichnamige interaktive Programm durch seine Vervollständigung leichter bedienbar macht.
600 .\" Die Zsh kennt die Formatierungen, die die Ksh kennt. typeset - oben schon kurz bei assoziativen Variabelfeldern erwähnt - ist ein mächtiger Formatierbefehl der Ksh. Mit diesen Formatierungsregeln lassen sich Ausgaben auf unterschiedliche Weise formatieren.
602 .\" typeset -L2 name=werteintrag ;print "[$name]"
603 .\" gibt linksformatiert "[we]" aus, die ersten 2 Buchstaben, umrahmt von [].
605 .\" typeset -lL20 name=WERT;print "[$name]"
606 .\" gibt in Kleinbuchstaben (-l für lower) "[wert ]" aus, wobei 20 - 11 Leerzeichen eingefügt werden.
608 .\" typeset -r RPROMPT=%n
609 .\" schützt den Rechtsprompt vor einem versehentlichen Überschreiben. Die Variable ist jetzt read-only und zsh warnt einen mit "zsh: read-only variable: RPROMPT ". Alle typeset-Befehle können mit einem - statt dem + aufgehoben werden. (Siehe man zshbuiltins unter typeset)
610 .\" Zusätzlich zu typeset kann man auch durch sogenannte Modifier die Ausgabe von print verändern. Beispiel:
613 .\" print "[${(Ll:20:)name}]"
614 .\" ergibt genau die selbe Ausgabe wie
616 .\" typeset -lL20 name
617 .\" Seit Zsh 4.1.1 kann man mit
619 .\" printf "%20s\n" ${(L)a}
620 .\" ähnlich wie in der gleichnamigen C-Funktion auch dieses Ergebnis bekommen, ohne den externen printf-Befehl nutzen zu müssen.
621 .\" Die Ausgabe von Dateinamen kann mittels sogenannter Qualifier spezifiziert werden (siehe man zshexpn unter Glob Qualifier). Beispiele:
623 .\" print -l *(m-1) # listet nur Dateien zeilenweise auf, die vor
624 .\" # bis zu einem Tag modifiziert wurden
626 .\" print -l *(a1) # listet Dateien zeilenweise auf, auf die vor einem
627 .\" # Tag zugegriffen wurde
629 .\" print -l *(@) # listet nur die Links zeilenweise auf
631 .\" ls -doF *(/) # findet nur die Verzeichnisse
633 .\" chmod 640 *(W) # verändert die Rechte aller Dateien, in die
634 .\" # jeder schreiben darf, denn das ist ja meistens
635 .\" # besonders riskant!
638 .\" grep name *(.) # findet nur noch reine Dateien. Damit ist
639 .\" # die unsinnige Meldung "grep: bla: Is a directory"
640 .\" # für alle Zeiten vermeidbar.
641 .\" Um einmal wieder an alte schlechtere Zeiten erinnert zu werden, könnte man auch 'grep name *(^.@)' eingeben. Hiermit werden alle Dateien aufgelistet, mit denen grep nichts anfangen kann, denn '^' ist das Nicht-Zeichen :).
644 .\" gg() { grep -wE "$1" *(.) | less -r }
645 .\" könnte eine kleine Zsh-Funktion sein, um gezielt nach einem Wort und unter Zuhilfenahme von regulären Ausdrücken zu suchen. Ich persönlich (Matthias) benutze allerdings lieber Perl für solche Dinge und habe dafür das Perl-Programm mg entdeckt.
646 .\" Ein sehr schneller Befehl, um DOS-Dateien (keine Verzeichnise) zu Dateien mit kleinen Buchstaben zu machen ist:
648 .\" for i in [A-Z][A-Z]*(.); do mv $i ${i:l} ;done
649 .\" Der Qualifier :l (für lowercase) leistet hier ganze Arbeit.
652 .\" gibt zeilenweise Dateien aus, die über 3 Megabyte groß sind.
653 .\" Ich kann unter der Zsh komprimierte Email-Pakete lesen, ohne mich zuerst um das Entpacken kümmern zu müssen. Das geht bei gzip-gepackten Dateien z.B. so:
655 .\" mutt -f =(zcat mailfold*.gz)
656 .\" In den =() steht dabei die Aktion, die mit einer Datei gemacht wird, es wird dabei eine temporäre Datei erzeugt und mit ihr z.B. mutt -f aufgerufen. Ein anderes Beispiel:
658 .\" mutt -f =(grepmail "Mustafa Mustermann" ~/mbox)
659 .\" sucht alle Emails von Mustafa Mustermann aus einer sehr großen Email-Datei namens mbox mittels grepmail, einem sehr mächtigen Perl-Programm zum Herausfiltern von Emails, welche einem bestimmten Kriterium entsprechen, heraus. Die temporäre Datei wird selbstverständlich nachher wieder gelöscht.
660 .\" mutt ist ein sehr schönes Mail-Programm, welches auch auf der Kommandozeile funktioniert, das wir sehr empfehlen können. Mit 'mutt -f' liest mutt nicht aus /var/spool/mail sondern die Email-Datei, hier mehrere Emaildateien. Ein anderes Beispiel:
663 .\" lynx -force_html -dump =(bzip2 -cd $1 | grep $2)
665 .\" ermöglicht es, mit lynxbz bzip2-gepackte HTML-Seiten nach einem Begriff zu untersuchen. Nötig wird dieser Mechanismus, wenn ein Programm lseek benötigt. (Siehe man 3 lseek)
666 .\" Wird keine temporäre Datei benötigt, dann kann man wie auch bei der Bash '<()' verwenden. Damit erspart man sich dann die manuelle Verwendung von /proc/self/fd oder die manuelle Erzeugung einer "named pipe":
668 .\" lynx -force_html <( gzip -cd komprimiert.html.gz )
669 .\" ist ein Beispiel, bei dem lynx die Ausgabe von 'gzip -cd komprimiert.html.gz' verarbeitet.
670 .\" Durch intelligente Kommunikation verschiedener Prozesse wird es möglich, dass man zwei Pseudodateien erzeugen und miteinander vergleichen kann: In Shellkreisen wird dies als 'named pipe' bezeichnet, die die Zsh indirekt erzeugt.
672 .\" diff <(zcat erste_datei.gz) <(zcat zweite_datei.gz)
673 .\" vergleicht den Inhalt von zwei komprimierten Dateien miteinander.
674 .\" Nach Setzung von READNULLCMD=less lässt sich eine Datei mit:
677 .\" unter less angucken. Einfach ein < vor die Datei setzen.
678 .\" Es ist ohne Probleme möglich, die Standardausggabe an mehrere Dateien umzulenken:
680 .\" ls >datei1 >datei2 >datei3
683 .\" ls >> datei1 >> datei2
684 .\" Man kann auch die Standardeingabe von mehreren Dateien empfangen:
686 .\" less < datei1 < datei2
687 .\" Es ist möglich, eine Umlenkung in eine Datei und gleichzeitig an eine Pipe zu bewerkstelligen:
689 .\" make >logfile | grep Error
690 .\" Mit ls -lL =emacs kann man beispielsweise in jedem Verzeichnis schauen, wie groß 'emacs' genau ist. Man muss nicht mehr den Pfad angeben. Die Zsh schaut dabei selbst im Pfad nach, wenn man emacs im Pfad hat. Man kann auch bequem Dateien, die im Pfad stehen, auf diese Art editieren.
693 .\" editiert eine C-Funktion, wenn sie im Pfad gefunden werden kann.
694 .\" Statt eines sehr expliziten aber umständlich zu tippenden find-Befehls kann under der Zsh ** als rekursives Kürzel verwendet werden. Mit:
696 .\" print -l **/*.html
697 .\" findet man alle HTML-Seiten, die in allen Verzeichnissen unterhalb des jetzigen Verzeichnisses vorhanden sind und gibt sie auf je einer Zeile (-l) aus.(**=Rekursion)
700 .\" print -l **/datei.html # sucht die bestimmte Datei in allen
701 .\" # vom aktuellen Verzeichnis abgehenden
702 .\" # Verzeichnissen und gibt genau sie aus.
704 .\" print -l **/*.html~datei.html # gibt alle HTML-Seiten
705 .\" # mit Ausnahme von datei.html zeilenweise aus.
707 .\" grep name **/*.txt # sucht in allen Texten unterhalb des
708 .\" # gegenwärtigen Verzeichnisses nach Dateien
709 .\" # mit Endung .txt.
710 .\" Mit vared kann man alle Umgebungsvariablen editieren. Das finden wir praktisch, weil wir sofort die Variable erreichen und nicht erst in einer Datei wie .zshrc nach ihr suchen müssen. Außerdem wirkt das Editieren der Variablen natürlich sofort.
711 .\" Der Befehl dirs -v zeigt alle Verzeichnisse, in denen man in einer Sitzung gewesen ist zeilenweise an. Wenn man
712 .\" setopt autopushd setzt, kann man nun mit cd +2 das vorletzte Verzeichnis erreichen.
713 .\" Mit der Zsh kann man sehr lange Unterverzeichnisse im Prompt mit einem kurzem oder signifikanteren Namen (named directory) versehen und dann mit ~name aufrufen. Das ist insbesondere dann sehr praktisch, wenn man in einem sehr entfernten Ordner von '/' aus gesehen arbeitet.
714 .\" Ich (Matthias) habe mir eine kleine Zsh-Funktion geschrieben, die mir aus einem langem Verzeichnisnamen einen kurzen erzeugt:
718 .\" NAMED_DIRECTORY=$PWD:t; # der Name des jetzigen Verzeichnisses wird
719 .\" # an NAMED_DIRECTORY ohne die Hierarchie übergeben.
720 .\" # :t steht für tail.
721 .\" eval $NAMED_DIRECTORY=$PWD; # es findet die Setzung eines named directory statt.
722 .\" cd ~$NAMED_DIRECTORY; # es wird in das named directory gesprungen.
723 .\" # ist mit dem bestehenden Verzeichnis identisch
724 .\" # aber der Name ist kürzer im Prompt.
726 .\" Eine außerdem sehr praktische Möglichkeit besteht darin, dass man jetzt nicht mehr den ganzen Pfadnamen angeben muss, wenn man eine Datei verschiebt. Z.B.:
729 .\" könnte die Datei bequem nach /usr/local/man/man1/ verschieben, wenn man lm1=/usr/local/man/man1 gesetzt hat.
730 .\" Bei der Prompt-Darstellung gibt es zwei Möglichkeiten: Entweder weisst man am Ende auch noch den letzten Slash zu: info=/usr/local/info/ Dann wird im Prompt der ganze Name dargestellt. cd ~info springt zwar nach /usr/local/info, aber im Prompt steht:
733 .\" Möchte man aber den kurzen Prompt haben, dann muss man so zuweisen:
735 .\" info=/usr/local/info
736 .\" -also ohne Slash am Ende.
737 .\" Die Option autocd erlaubt es, nur den Namen eines Ordners anzugeben. Bei Eindeutigkeit wird dann sofort in diesen Ordner gesprungen. Z.B. springt bin «enter» dann sofort in das bin-Verzeichnis.
738 .\" Es gibt keinen Fehler bei Farbprompts wie unter der Bash1-Shell. Gerade bei der Gliederung des Prompts ist das besonders wichtig. Da die üblichen Escape-Sequenzen sehr unleserlich sind gibt es in der Zsh eine besonders elegante Möglichkeit, um Farben zu definieren. Ein Beispiel:
740 .\" autoload -U colors && colors
741 .\" echo "$fg_bold[red]zsh $fg_no_bold[white]is $bg[blue]$fg_bold[green]nice"
742 .\" Mit RPROMPT lässt sich ein PROMPT auf der rechten Seite definieren:
743 .\" RPROMPT=%l zeigt beispielsweise an, auf welchem Rechner man sich befindet.
744 .\" RPROMPT=%n zeigt den Benutzer an.
745 .\" RPROMPT=%T zeigt die Zeit an.
746 .\" RPROMPT=%D{%d.%m.%y} zeigt das Datum nach deutscher Darstellung an.
747 .\" Selbstverständlich kennt die Zsh auch eine Korrekturmöglichkeit bei falscher Eingabe, die aber nur dann wirksam wird, wenn man das wirklich eingestellt hat. Man setzt in einen solchem Fall einfach:
749 .\" setopt autocorrect
750 .\" Die Korrektur kann durch Setzung eines
752 .\" alias <befehl>=nocorrect <befehl>
753 .\" verhindert werden.
754 .\" Um darüber informatiert zu werden, wer alles außer mir sich eingeloggt hat, gibt es das Kommando watch wie unter der Tcsh.
758 .\" listet z.B. alle Benutzer auf, die nicht ich sind :)
759 .\" Hierbei kann das Format der Ausgabe geändert werde:
762 .\" WATCHFMT='%n eingeloggt auf Terminal %l von %M seit %T '
763 .\" Wählt man watch=(@vorsicht_ist_angesagt), so werden alle Benutzer aufgeführt, die von dem Server vorsicht_ist_angesagt eingeloggt sind.
764 .\" Positiv herum kann man so natürlich auch alle Freunde erkennen lassen:
766 .\" watch=( < ~/.freunde root)
767 .\" liest alle Freunde aus der Datei .friends in das Feld watch zusätzlich zu root ein. So kann man schnell erkennen, wenn sich Freunde einloggen.
768 .\" Es gibt in der Zsh einen sehr bequemen Wiederholungsbefehl, der von der tcsh abgeschaut ist: repeat. Möchte man z.B. einen Werbemailer böswillig strafen, dann könnte man das so machen:
771 .\" repeat 100 mail -s "spams suck" badcompany@devilsheart.com < flame
772 .\" Dabei sollte allerdings bedacht werden, dass man damit meist harmlose Benutzer trifft, die schlechte Passworte haben und deshalb Räubern auf den Leim gegangen sind.
773 .\" Ruft man ein altes Kommando mit !?kommando auf, hat man die Möglichkeit, vor der erneuten Ausführung zu schauen, ob es sich hierbei auch um das gewünschte Kommando handelt. Man drückt dazu einfach «TAB». Ebenso kann man sich auch die genau betroffenen Dateien eines global wirkenden Befehles (z.B. 'ls *.html') mit «TAB» ansehen.
774 .\" Gerade eben getippte Worte auf der Kommandozeile können mit !# genauer wiedergegeben werden als bei Bash/Tcsh/Ksh. Man gibt einfach an, wo wiederholt werden soll - z.B.:
776 .\" echo ein_langes_wort zweites_langes_wort drei !#1-2
777 .\" schreibt auf den Bildschirm: 'ein_langes_wort zweites_langes_wort drei ein_langes_wort zweites_langes_wort'.
778 .\" Um die Funktion funct alle 300 Sekunden auszuführen führt man einfach folgenden Befehl aus:
780 .\" periodic funct() PERIOD=300 fortune -s
781 .\" Anmerkung: Allerdings muss dazu auch am Prompt ein Befehl eingegeben werden, sonst kann man natürlich nichts auf dem Bildschirm sehen.
782 .\" Die Zsh kennt den '..' Operator von Pascal (und Perl):
784 .\" echo {1..7} "\nWo ist denn die Bash geblieben?"
788 .\" Wo ist denn die Bash geblieben?
789 .\" Die Zsh hat in ihrer sehr mächtigen HISTORY CONTROL ein run-help Kommando, mit dem zu einem Buffer gezielt Informationen abgerufen werden können. Voreingestellt ist hier der Aufruf der Manpage zu dem Kommando. Verändern könnte man diesen Aufruf, in dem man einfach aus:
791 .\" alias run-help=man # ein ->
792 .\" alias run-help=info
795 .\" man_zshall() man zshall # und nachfolgendes Deklarieren von
796 .\" zle -N man_zshall # kann durch Definition von
797 .\" bindkey '^g' man_zshall # nun immer bei Control-G ausgeführt werden.
798 .\" sched ist ein interner Befehl zum automatischen, zeitgebundenen Abarbeiten von Kommandos ähnlich wie bei 'at'. Dabei werden die Kommandos aber nicht ausgeführt und dann als E-Mail zugeschickt, sondern gelangen erst einmal in den Puffer und werden beim nächsten Kommando erst auf dem Bildschirm ausgegeben.
800 .\" sched +0:10 figlet "Du musst jetzt los"
801 .\" führt in 10 Minuten in Großschrift auf dem Bildschirm eine Warnung zum Gehen aus. Dabei ist allerdings das Durchführen des Befehls abhängig von der Eingabe eines nächsten Befehls.
804 Convert images from foo.gif to foo.png:
806 $ for i in **/*.gif; convert $i $i:r.png
810 Download files created with LaTeX2HTML (e.g. the ZSH-Guide):
812 $ for f in http://zsh.sunsite.dk/Guide/zshguide{,{01..08}}.html; do
813 lynx -source $f >${f:t}
818 Make with dpkg a master-list of everyfile that it has
821 $ diff <(find / | sort) <(cat /var/lib/dpkg/info/*.list | sort)
825 Replace this color escape-sequences:
827 $ autoload colors ; colors
828 $ print "$bg[cyan]$fg[blue]Welcome to man zsh-lovers" >> $TTY
832 Get ASCII value of a character:
834 $ char=N ; print $((#char))
838 Filename suffix. Note: (N) activates setopt nullglob only for this loop.
840 $ for i in *.o(N); do
846 Rename files: 'FOO' to 'foo':
848 $ for i in *(.); mv $i ${i:l}
852 Rename files: 'bar' to 'BAR':
854 $ for i in *(.); mv $i ${i:u}
858 Show all suid-files in $PATH:
860 $ ls -latg ${(s.:.)PATH} | grep '^...s'
862 .\"#######################################################
864 .\"#######################################################
865 .SS "ZMV - multiple move with zsh"
866 Requires 'autoload zmv'. Some examples:
869 Move serially all files (foo.foo > 1.foo, fnord.foo > 2.foo, ..).
872 1.c asd.foo bla.foo fnord.foo foo.fnord foo.foo
873 $ c=1 zmv '*.foo' '$((c++)).foo'
875 1.c 1.foo 2.foo 3.foo 4.foo foo.fnord
879 See above, but now only files with a filename >= 30 chars.
880 .\" Anmerkung: es gibt da ein noch genaueres Pattern - FIXME
882 $ c=1 zmv "${(l:30-4::?:)}*.foo" '$((c++)).foo'
886 Replace spaces in filenames with a underline.
888 $ zmv '* *' '$f:gs/ /_'
892 Change the suffix from *.sh to *.pl.
894 $ zmv -W '*.sh' '*.pl'
898 Lowercase/uppercase all files and directories.
900 $ zmv '(*)' '${(L)1}' for lowercase
901 $ zmv '(*)' '${(U)1}' for uppercase
905 Remove the suffix *.c from all c-files.
911 Uppercase only the first letter of all *.mp3 - files.
913 $ zmv '([a-z])(*).mp3' '${(C)1}$2.mp3'
917 Copy the target `README' in same directory as each `Makefile'.
919 $ zmv -C '(**/)Makefile' '${1}README'
924 Rename pic1.jpg, pic2.jpg,.. to pic0001.jpg, pic0002.jpg,...
926 $ zmv 'pic(*).jpg' 'pic${(l:4::0:)1}.jpg'
927 $ zmv '(**/)pic(*).jpg' '$1/pic${(l:4::0:)2}.jpg' # recursive
929 .\"#######################################################
931 .\"#######################################################
934 See also \fIman zshmodules\fP\&.
935 Don't forget to run \fIzmodload \-i MODULENAME\fP
936 before using a module\&. Example: \fIzmodload -i
942 Builtins for manipulating POSIX\&.1e (POSIX\&.6) capability (privilege) sets\&.
945 A builtin that can clone a running shell onto another terminal\&.
947 Creates a forked instance of the current shell ($! is set to zero) and
948 execute ``command'' on /dev/tty8 (for this example):
951 $ clone /dev/tty8 && (($! == 0)) && exec command
955 The \fBcompctl\fP builtin for controlling completion\&.
958 The basic completion code\&.
961 Completion listing extensions\&.
964 A module with utility builtins needed for the shell function based
968 Some date/time commands and parameters\&.
970 Do not have GNU date? Let's replace it:
972 $ alias datereplacement='strftime "%Y-%m-%d" $EPOCHSECONDS'
973 $ export DATE=`datereplacement`
978 A ZLE function duplicating EMACS' \fBzap\-to\-char\fP\&.
981 An example of how to write a module\&.
984 Some basic file manipulation commands as builtins\&.
986 # search a directory for files containing a certain string then copy those files to another directory.
988 $ cp $(grep -lZr foobar .) otherdirectory
992 Access to external files via a special associative array\&.
994 # grepping for two patterns
997 $ print -l ./**/*(DN.e{'z=$mapfile[$REPLY] &&
998 [[ $z = *$pattern1* && $z = *$pattern2* ]]'})
999 # or a solution in combination with zsh/pcre
1000 $ zmodload -i zsh/mapfile zsh/pcre
1002 $ pattern2="bar foo"
1003 $ pcre_compile "(?s)(?=.*?$pattern1).*?$pattern2"
1005 $ print -l ./**/*(DN.e{'pcre_match $mapfile[$REPLY]'})
1007 # equivalent for ``less /etc/passwd | grep -v root''
1009 $ print -rl -- ${${=mapfile[/etc/passwd]}:#*root*}
1010 # or - for case insensitive
1011 $ setopt extendedglob
1012 $ print -rl -- ${${=mapfile[/etc/passwd]}:#*(#i)root*}
1014 # If a XML-file contains stuff like ``<TAGA/>'' and ``<TAGB/>'', number this empty tags
1015 # (ones ending in '/>') so if encountered in the same order, the preceeding tags would become
1016 # ``<TAGA/>1</TAGA>'' and ``<TAGB/>2</TAGB>''
1018 $ apfile[data.xml.new]=${(S)mapfile[data.xml]//\
1019 > (#im)<TAGA>*<\/TAGA>/<TAGA>$((++cnt))<\/TAGA>}
1021 # removing all files in users Maildir/new that contain ``filename="gone.src''
1022 $ zmodload zsh/{files,mapfile}
1023 $ rm -f /u1/??/*/Maildir/new/100*(.e{'[[ $mapfile[$REPLY] == *filename=\"gone.scr\"* ]]'})
1025 # Grep out the Title from a postscript file and append that value to the end of
1028 $ zmv '(*).ps' '$1-${${${mapfile[$f]##*%%Title: }%% *}//[^a-zA-Z0-9_]/}.ps'
1032 Standard scientific functions for use in mathematical evaluations\&.
1034 $ echo $(( sin(1/4.0)**2 + cos(1/4.0)**2 - 1 ))
1035 -1.1102230246251565e-16
1036 $ echo $(( pi = 4.0 * atan(1.0) ))
1038 $ echo $(( f = sin(0.3) ))
1040 $ print $(( rand48(seed) ))
1045 Access to internal hash tables via special associative arrays\&.
1048 Interface to the PCRE library\&.
1050 Important: requires zsh compiled with pcre-support. Check
1051 whether your version supports pcre via `ldd =zsh | grep
1054 PCRE provides support for Perl's regular expressions (regex). You
1055 have to compile a regex and can match it afterwards using
1060 $ pcre_compile '\\s\\d.\\d{3}\.\\d{3} Euro' &&\\
1061 pcre_match ' 1.000.000 Euro' &&\\
1062 echo "matches" || echo "does not match"
1064 Note: if you are using complex regular expressions you can
1065 improve speed via pcre_study.
1068 A builtin that provides a timed execution facility within the shell\&.
1070 \fBzsh/net/socket\fP
1071 Manipulation of Unix domain sockets
1073 $ zmodload zsh/net/socket
1075 # ``-l'': open a socket listening on filename
1076 # ``-d'': argument will be taken as the target file descriptor for the
1078 # ``3'' : file descriptor. See ``A User's Guide to the Z-Shell''
1079 # (3.7.2: File descriptors)
1081 # ``-a'': accept an incoming connection to the socket
1082 $ zsocket -a -d 5 3 # accept a connection
1090 $ zmodload zsh/net/socket
1091 $ zsocket -l -d 3 /tmp/mysocket # open listening socket
1092 $ zsocket -a -d 4 3 # accept a connection
1093 $ zsocket -a -d 5 3 # accept a connection
1095 $ echo Hi there also >&5
1096 $ exec 4>&- 5>&- 3>&-
1101 $ zmodload zsh/net/socket
1102 $ zsocket -d 3 /tmp/mysocket # connect to /tmp/socket
1103 $ zsocket -d 4 /tmp/mysocket # connect to /tmp/socket
1104 $ read msg <&3; echo got: "$msg on fd 3"
1105 $ read msg <&4; echo got: "$msg on fd 4"
1110 A builtin command interface to the \fBstat\fP system call\&.
1112 Get size of a file in bytes:
1114 $ zmodload -i zsh/stat
1115 $ stat -L +size file
1123 Comparing file dates:
1127 $ touch bar & sleep 5 & touch foo
1128 $ echo $file1 is $(( $(stat +mtime $file2) - $(stat +mtime $file1) )) seconds older than $file2.
1129 bar is 5 seconds older than foo
1132 List the files of a disk smaller than some other file:
1134 $ stat -A max +size some-other-file
1135 $ print -rl ./**/*(D.L-$max)
1138 List the top 100 biggest files in a disk:
1140 $ ls -fld ./**/*(d`stat +device .`OL[1,100])
1143 Get only the user name and the file names from (like ls -l * | awk '{print $3" " $8}'):
1146 > stat -sA user +uid -- "$file" &&
1147 > print -r -- "$user" "$file"
1151 Get the difference between actual bytes of file and allocated bytes of file:
1153 $ print $(($(stat +block -- file) * 512 - $(stat +size -- file)))
1158 $ stat +size ./*(DOL[1])
1159 # ``D'' : to include dot files (d lowercase is for device)
1160 # ``O'' : reverse Ordered (o lowercase for non-reverse order)
1161 # ``L'' : by file Length (l is for number of links)
1162 # ``[1]'': return only first one
1165 Delete files in a directory that hasn't been accessed in the last ten days
1166 and send ONE mail to the owner of the files informing him/her of the files' deletion:
1168 $ zmodload zsh/stat zsh/files
1169 $ typeset -A f; f=()
1170 $ rm -f /path/**/*(.a+10e{'stat -sA u +uidr $REPLY; f[$u]="$f[$u]$REPLY"'})
1171 $ for user (${(k)f}) {print -rn $f[$user]|mailx -s "..." $user}
1174 Get a "ls -l" on all the files in the tree that are younger than a specified age:
1176 $ for d (. ./**/*(N/m-2))
1177 > print -r -- $'\n'$d: && cd $d && {
1179 > stat -F '%b %d %H:%M' -LsAs -- $f &&
1180 > print -r -- $s[3] ${(l:4:)s[4]} ${(l:8:)s[5]} \\
1181 > ${(l:8:)s[6]} ${(l:8:)s[8]} $s[10] $f ${s[14]:+-> $s[14]}
1186 Get file creation date:
1188 $ stat -F '%d %m %Y' +mtime ~/.zshrc
1190 $ stat -F '%D' +mtime ~/.zshrc
1195 A builtin interface to various low\-level system features\&.
1198 Manipulation of TCP sockets
1201 Interface to the termcap database\&.
1203 $ zmodload -ab zsh/termcap echotc
1204 $ GREEN=`echotc AF 2`
1205 $ YELLOW=`echotc AF 3`
1207 $ BRIGHTRED=`echotc md ; echotc AF 1`
1208 $ print -l ${GREEN}green ${YELLOW}yellow ${RED}red ${BRIGHTRED}brightred
1212 Interface to the terminfo database\&.
1215 A builtin FTP client\&.
1217 Write ftp scripts as though shell:
1220 $ autoload -U zfinit && zfinit
1221 $ zfparams www.example.invalid myuserid mypassword
1224 $ zfls -l zsh-lovers.html
1225 $ zfput zsh-lovers.html
1226 $ zfls -l zsh-lovers.html
1229 Automatically transfer files using FTP with error checking:
1231 $ zftp open host.name.invalid user passwd || exit
1232 $ zftp get /remote/file > /local/file; r=$?
1233 $ zftp close && exit r
1236 Compress and ftp on the fly:
1238 $ zftp open host.name.invalid user password
1239 $ zftp get $file | bzip2 > ${file}.bz2
1243 Long list of files on a ftp:
1245 $ autoload -U zfinit
1248 $ zfcd /some/remote/Dir
1249 $ cd /some/local/Dir
1252 If the list.txt is located on the remote host, change to
1253 $ zfget ${(f)"$(zftp get /path/to/remote/list.txt)"}
1254 $ zfget ${(f)"$(cat list.txt)"}
1259 The Zsh Line Editor, including the \fBbindkey\fP and \fBvared\fP builtins\&.
1261 \fBzsh/zleparameter\fP
1262 Access to internals of the Zsh Line Editor via parameters\&.
1265 A module allowing profiling for shell functions\&.
1268 A builtin for starting a command in a pseudo\-terminal\&.
1270 $ zmodload -i zsh/zpty
1272 # ``-r'': read the output of the command name.
1274 $ zpty -r PW z '*password:'
1275 # send the to command name the given strings as input
1277 $ zpty -r PW z '*password:'
1279 # | The second form, with the -d option, is used to delete commands
1280 # | previously started, by supplying a list of their names. If no names
1281 # | are given, all commands are deleted. Deleting a command causes the HUP
1282 # | signal to be sent to the corresponding process.
1287 Block and return when file descriptors are ready\&.
1292 | $ stty -icanon min 0 time 50
1295 | $ case "$yesno" in
1300 $ if zselect -t 500 -r 0 && read yesno && [ yes = "$yesno" ]; then
1308 Some utility builtins, e\&.g\&. the one for supporting configuration via
1312 .\"#######################################################
1314 .\"#######################################################
1320 $ ls -l =zsh # is like: 'ls -l /path/to/zsh' or 'ls -l `which zsh`'
1324 Process substitution:
1326 $ (vi =(cmd)) # edit output of 'cmd' (called process substitution).
1330 Substitution of variables:
1343 .\"#######################################################
1345 .\"#######################################################
1349 Suffix aliases are supported in zsh since version 4.2.0.
1358 Now pressing return-key after entering 'foobar.vim' starts vim
1359 with foobar.vim. Calling a html-file runs browser w3m. 'www.zsh.org'
1360 and pressing enter starts w3m with argument www.zsh.org.
1363 Global aliases can be used anywhere in the command line.
1366 $ alias -g C='| wc -l'
1367 $ grep alias ~/.zsh/* C
1371 Some more or less useful global aliases (choose whether they
1372 are useful or not for you on your own):
1374 alias -g ...='../..'
1375 alias -g ....='../../..'
1376 alias -g .....='../../../..'
1377 alias -g CA="2>&1 | cat -A"
1378 alias -g C='| wc -l'
1379 alias -g D="DISPLAY=:0.0"
1380 alias -g DN=/dev/null
1381 alias -g ED="export DISPLAY=:0.0"
1382 alias -g EG='|& egrep'
1383 alias -g EH='|& head'
1384 alias -g EL='|& less'
1385 alias -g ELS='|& less -S'
1386 alias -g ETL='|& tail -20'
1387 alias -g ET='|& tail'
1388 alias -g F=' | fmt -'
1389 alias -g G='| egrep'
1391 alias -g HL='|& head -20'
1392 alias -g §k="*~(*.bz2|*.gz|*.tgz|*.zip|*.z)"
1393 alias -g LL="2>&1 | less"
1395 alias -g LS='| less -S'
1396 alias -g MM='| most'
1398 alias -g NE="2> /dev/null"
1399 alias -g NS='| sort -n'
1400 alias -g NUL="> /dev/null 2>&1"
1402 alias -g R=' > /c/aaa/tee.txt '
1403 alias -g RNS='| sort -nr'
1405 alias -g TL='| tail -20'
1407 alias -g US='| sort -u'
1408 alias -g VM=/var/log/messages
1409 alias -g X0G='| xargs -0 egrep'
1410 alias -g X0='| xargs -0'
1411 alias -g XG='| xargs egrep'
1412 alias -g X='| xargs'
1414 .\"#######################################################
1416 .\"#######################################################
1418 Array parameters [array_name=(value1 value2 ... valueN)].
1425 .\"#######################################################
1427 .\"#######################################################
1428 .SS "SHELL-SCRIPTING"
1429 This section provides some examples for often needed
1430 shellscript-stuff. Notice that you should not use
1431 '#!/bin/sh' but '#!/bin/zsh' as the shebang-line because
1432 otherwise most examples won't work.
1434 Parse options in shellscripts. Example taken from ZWS by
1435 Adam Chodorowski (http://www.chodorowski.com/projects/zws/):
1443 zparseopts -K -- p:=o_port r:=o_root h=o_help
1444 if [[ $? != 0 || "$o_help" != "" ]]; then
1445 echo Usage: $(basename "$0") "[-p PORT] [-r DIRECTORY]"
1453 if [[ $root[1] != '/' ]]; then root="$PWD/$root"; fi
1455 # now use the function:
1459 .\"#######################################################
1460 .SS "MISC\-EXAMPLES"
1461 Hint: A list of valid glob Qualifiers can be found in zshexpn(1). See
1462 ``man 1 zshexpn | less -p'' Qualifiers for details.
1464 Load all available modules at startup
1468 $ for md ($module_path) m=($m $md/**/*(*e:'REPLY=${REPLY#$md/}'::r))
1472 Rename all MP3-Files from ``name with spaces.mp3'' to ``Name With
1475 $ for i in *.mp3; do
1476 > mv $i ${${(C)i}:s/Mp3/mp3/}
1480 Download with LaTeX2HTML created Files (for example the ZSH\-Guide):
1482 $ for f in http://zsh.sunsite.dk/Guide/zshguide{,{01..08}}.html; do
1483 > lynx -source $f >${f:t}
1487 Replace the unreadable Escape-Sequences:
1489 $ autoload colors ; colors
1490 $ print "$bg[cyan]$fg[blue]You are an zsh user" >> /dev/pts/3
1493 Filename\-Expansion.
1495 (N) activates setopt nullglob only for this loop.
1497 $ for i in *.o(N); do
1502 Re-linking broken links:
1504 $ for f in ./**/*(-@); do
1505 > stat +link -A l $f
1506 > (cd $f:h & [[ -e $l.gz ]]) & ln -sf $l.gz $f
1510 Show me all the .c files for which there doesn't exist a .o file:
1512 $ c=(*.c) o=(*.o(N)) eval 'ls ${${c:#(${~${(j:|:)${o:r}}}).c}:?done}'
1515 Load all available modules at startup:
1519 $ for md ($module_path) m=($m $md/**/*(*e:'REPLY=${REPLY#$md/}'::r))
1523 Rename all files within a directory such that their names get a numeral prefix in the default sort order:
1525 $ i=1; for j in *; do mv $j $i.$j; ((i++)); done
1526 $ i=1; for f in *; do mv $f $(echo $i| awk '{ printf("%03d", $0)}').$f; ((i++)); done
1527 $ integer i=0; for f in *; do mv $f $[i+=1].$f; done
1530 Find (and print) all symbolic links without a target within the current dirtree:
1532 $ $ file **/*(D@) | fgrep broken
1533 $ for i in **/*(D@); [[ -f $i || -d $i ]] || echo $i
1534 $ echo **/*(@-^./=%p)
1538 List all plain files that do not have extensions listed in `fignore':
1540 $ ls **/*~*(${~${(j/|/)fignore}})(.)
1541 # see above, but now omit executables
1542 $ ls **/*~*(${~${(j/|/)fignore}})(.^*)
1545 Print out files that dont have extensions (require setopt extendedglob dotglob):
1547 $ printf '%s\n' ^?*.*
1550 List files in reverse order sorted by name:
1552 $ print -rl -- *(On)
1554 $ print -rl -- *(^on)
1557 Synonymic to ``ps ax | awk '{print $1}''':
1559 $ print -l /proc/*/cwd(:h:t:s/self//)
1562 Get the PID of a process (without ``ps'', ``sed'', ``pgrep'', .. (under Linux):
1566 > for i in /proc/<->/stat
1568 > [[ "$(< $i)" = *\\((${(j:|:)~@})\\)* ]] && echo $i:h:t
1573 for X in 'n' 'o' 'p' 'q' 'r' 's' 't' 'u' 'v' 'w' 'x' 'y'; do ...:
1575 $ for (( i = 36#n; i <= 36#y; i++ )); do
1576 > print ${$(([##36]i)):l}
1578 # or in combination with ``dc''
1579 $ print {$((##n))..$((##y))}P\ 10P | dc
1581 $ eval print '${$(([##36]'{$((36#n))..$((36#y))}')):l}'
1584 Foreach in one line of shell:
1586 $ for f (*) print -r -- $f
1589 Copy a directory recursively without data/files:
1595 $ find . -type d -exec env d="$dest_root" sh -c ' exec mkdir -p -- "$d/$1"' '{}' '{}' \;
1598 If `foo=23'', then print with 10 digit with leading '0':
1601 $ print ${(r:10::0:)foo}
1604 Find the name of all the files in their home directory that have more than 20 characters in their file names:
1606 print -rl $HOME/${(l:20::?:)~:-}*
1611 $ print -r -- ${(qq)m} > $nameoffile # save it
1612 $ eval "m=($(cat -- $nameoffile)" # or use
1613 $ m=("${(@Q)${(z)"$(cat -- $nameoffile)"}}") # to restore it
1616 Get a "ls -l" on all the files in the tree that are younger than a specified age (e.g
1617 "ls -l" all the files in the tree that where modified in the last 2 days):
1622 This will give you a listing 1 file perl line (not like ls -R).
1623 Think of an easy way to have a "ls -R" style output with
1624 only files newer than 2 day old.
1626 $ for d (. ./**/*(/)) {
1627 > print -r -- $'\n'${d}:
1630 > (($#l)) && ls -ltd -- $l
1636 If you also want directories to be included even if their mtime
1637 is more than 2 days old:
1639 $ for d (. ./**/*(/)) {
1640 > print -r -- $'\n'${d}:
1643 > (($#l)) && ls -ltd -- $l
1649 And if you want only the directories with mtime < 2 days to be listed:
1651 $ for d (. ./**/*(N/m-2)) {
1652 > print -r -- $'\n'${d}:
1655 > (($#l)) && ls -ltd -- $l
1663 $ echo ${(l:42::-:)}
1664 # or use ``$COLUMS''
1665 $ echo ${(l:$COLUMNS::-:)}
1666 # and now with colors (require autoload colors ;colors)
1667 $ echo "$bg[red]$fg[black]${(l:42::-:)}"
1670 Redirect STDERR to a command like xless without redirecting STDOUT as well:
1673 # but this executes the command asynchronously. To do it synchronously:
1674 $ { { foo 1>&3 } 2>&1 | xless } 3>&1
1677 Rename all MP3-Files from name with spaces.mp3 to Name With Spaces.mp3:
1679 $ for i in *.mp3; do
1680 > mv $i ${${(C)i}:s/Mp3/mp3/}
1684 Match file names containing only digits and ending with .xml (requiresetopt kshglob):
1690 Remove all "non txt" files:
1695 Move 200 files from a directory into another:
1697 $ mv -- *([1,200]) /another/Dir
1700 Convert images (foo.gif => foo.png):
1702 $ for i in **/*.gif; convert $i $i:r.png
1705 Convert a collection of mp3 files to wave or cdr (e.g. file.wav -> file.mp3):
1707 $ for i (./*.mp3){mpg321 --w - $i > ${i:r}.wav}
1710 Download with LaTeX2HTML created Files (for example the ZSH-Guide):
1712 $ for f in http://zsh.sunsite.dk/Guide/zshguide{,{01..08}}.html; do
1713 > lynx -source $f >${f:t}
1717 Move all files in dir1 and dir2 that have line counts greater than 10 to another directory say "/more10":
1719 $ mv dir[12]/**/*.cr(-.e{'((`wc -l < $REPLY` > 10))'}) /more10
1722 Make with dpkg a master-list of everyfile that it has installed:
1724 $ diff <(find / | sort) <(cat /var/lib/dpkg/info/*.list | sort)
1727 Replace the unreadable Escape-Sequences:
1729 $ autoload colors ; colors
1730 $ print "$bg[cyan]$fg[blue]You are an zsh user" >> /dev/pts/3
1733 Get ASCII value of a character:
1735 $ char=N ; print $((#char))
1739 Note: The (N) says to use the nullglob option for this particular glob pattern.
1741 $ for i in *.o(N); do
1746 Rename files; i. e. FOO to foo and bar to BAR:
1748 $ for i in *(.); mv $i ${i:l} # `FOO' to `foo'
1749 $ for i in *(.); mv $i ${i:u} # `bar to `BAR'
1752 Show all suid-files in $PATH:
1754 $ ls -latg ${(s.:.)PATH} | grep '^...s'
1755 # or more complex ;)
1756 $ print -l ${^path}/*(Ns,S)
1757 # or show only executables with a user given pattern
1758 $ print -l ${^path}/*vim*(*N)
1761 gzip files when containing a certain string:
1763 $ gzip ${(ps:\0:)"$(grep -lZ foobar ./*.txt(.))"}
1766 A small one-liner, that reads from stdin and prints to stdout the first unique line
1767 i. e. does not print lines that have been printed before (this is similar to the unique
1768 command, but unique can only handle adjacent lines):
1770 $ IFS=$'\n\n'; print -rl -- ${(Oau)${(Oa)$(cat file;echo .)[1,-2]}}
1773 Lists every executable in PATH:
1775 $ print -l ${^path}/*(-*N)
1778 Match all .c files in all subdirectories, _except_ any SCCS subdirectories?
1780 $ ls **/*.c~(*/)#SCCS/*
1783 List all `README' - files case-insensitive with max. one typo:
1785 $ ls **/*(#ia2)readme
1788 Print version information of zsh:
1790 $ print $ZSH_VERSION
1794 Get hostspecific information:
1796 $ echo $MACHTYPE $VENDOR $OSTYPE
1800 Fast change of directories:
1802 alias ...='cd ../..'
1803 alias ....='cd ../../..'
1804 alias .....='cd ../../../..'
1805 alias ......='cd ../../../../..'
1806 alias .......='cd ../../../../../..'
1810 Mailpath: simple multiple mailpath:
1812 mailpath=($HOME/Mail/mbox'?new mail in mbox'
1813 $HOME/Mail/tux.u-strasbg'?new mail in tux'
1814 $HOME/Mail/lilo'?new mail in lilo'
1815 $HOME/Mail/ldap-fr'?new mail in ldap-fr')
1819 Mailpath: dynamic mailpath:
1822 for i in ~/Mail/Lists/*(.); do
1823 mailpath[$#mailpath+1]="${i}?You have new mail in ${i:t}."
1828 Avoid globbing on special commands:
1830 for com in alias expr find mattrib mcopy mdir mdel which;
1831 alias $com="noglob $com"
1835 For migrating your bashprompt to zsh use the script bash2zshprompt
1836 located in the zsh source distribution under 'Misc'.
1839 For migration from (t)csh to zsh use the c2z tool that
1840 converts csh aliases and environment and shell variables to
1841 zsh. It does this by running csh, and having csh report on
1842 aliases and variables. The script then converts these to zsh
1843 startup files. It has some issues and usage information that
1844 are documented at the top of this script.
1847 Here are functions to set the title and hardstatus of an
1848 \fBXTerm\fP or of \fBGNU Screen\fP to 'zsh' and the current
1849 directory, respectively, when the prompt is displayed, and
1850 to the command name and rest of the command line,
1851 respectively, when a command is executed:
1854 if [[ $TERM == "screen" ]]; then
1855 # Use these two for GNU Screen:
1856 print -nR $'\033k'$1$'\033'\\
1857 print -nR $'\033]0;'$2$'\a'
1858 elif [[ $TERM == "xterm" || $TERM == "rxvt" ]]; then
1859 # Use this one instead for XTerms:
1860 print -nR $'\033]0;'$*$'\a'
1870 local -a cmd; cmd=(${(z)1})
1871 title $cmd[1]:t "$cmd[2,-1]"
1874 Put the following line into your ~/.screenrc to see this fancy hardstatus:
1876 caption always "%3n %t%? (%u)%?%?: %h%?"
1880 Special variables which are assigned or you can assign:
1882 $ echo $LINENO $RANDOM $SECONDS $COLUMNS $HISTCHARS
1883 $ echo $UID $EUID $GID $EGID $USERNAME
1884 $ echo $fignore $mailpath $cdpath
1887 Show me all the .c files for which there doesn't exist a .o file:
1889 $ c=(*.c) o=(*.o(N)) eval 'ls ${${c:#(${~${(j:|:)${o:r}}}).c}:?done}'
1893 Find (and print) all symbolic links without a target within the current
1896 $ file **/*(D@) | fgrep broken
1897 $ for i in **/*(D@); [[ \-f $i || \-d $i ]] || echo $i
1898 $ echo **/*(@\-^./=%p)
1899 $ print \-l **/*(\-@)
1903 Rename files; i. e. FOO to foo and bar to BAR:
1905 $ for i in *(.); mv $i ${i:l} # `FOO' to `foo'
1906 $ for i in *(.); mv $i ${i:u} # `bar to `BAR'
1909 Show all suid-files in $PATH:
1911 $ ls \-latg ${(s.:.)PATH} | grep '^...s'
1914 List all `README' - files case-insensitive with max. one typo:
1916 $ ls **/*(#ia2)readme
1919 .SS (RECURSIVE) GLOBBING\-EXAMPLES
1920 Search for `README' in all Subdirectories
1922 $ print \-l **/README
1927 $ chmod 700 **/(.) # Only files
1928 $ chmod 700 **/(/) # Only directories
1931 List files beginning at `foo23' upwards (foo23, foo24, foo25, ..)
1936 Remove spaces from filenames
1938 $ for a in ./**/*\\ *(Dod); do mv $a ${a:h}/${a:t:gs/ /_}; done
1941 Show only all *.c and *.h - Files
1948 all *.c - files and ignore `foo.c'
1953 Show only world-readable files
1958 find and delete the files which are older than a given parameter
1959 (seconds/minutes/hours)
1961 # deletes all regular file in /Dir that are older than 3 hours
1962 $ rm -f /Dir/**/*(.mh+3)
1963 # # deletes all symlinks in /Dir that are older than 3 minutes
1964 $ rm -f /Dir/**/*(@mm+3)
1965 # deletes all non dirs in /Dir that are older than 30 seconds
1966 $ rm -f /Dir/**/*(ms+30^/)
1967 # deletes all files more than 6 hours old
1969 # deletes all folders, sub-folders and files older than one hour
1970 $ rm ./**/*(.Dmh+1,.DL0)
1971 # removes all files but the ten newer ones (delete all but last 10 files in a directory)
1974 Note: If you get a arg list too long, you use the builtin rm. For example:
1975 $ zmodload zsh/files ; rm -f **/*(mh+6)
1976 or use the zargs function:
1977 $ autoload zargs ; zargs **/*(mh+6) -- rm -f
1982 ./: to avoid problem with files starting with "\-"
1983 **/: recursively descend
1986 (<a>,<b>): files of <a> type or <b> type
1989 D: including dot files
1990 mh+1: whose [m]odification time, is more (+) than [1]
1994 D: including dot files
1998 If you want to remove empty directories afterwards:
2000 # ``/'' matches only directories and ``od'' sorted in depth order (so
2001 # that dir/subdir is removed before directory).
2002 $ rmdir ./**/*(/od) 2> /dev/null
2006 If you get a arg list too long, you use the builtin rm. For example:
2008 $ zmodload zsh/files ; rm -f **/*(mh+6)
2010 or use the zargs function:
2012 $ autoload zargs ; zargs **/*(mh+6) -- rm -f
2015 Delete only the oldest file in a directory:
2017 $ rm ./*filename*(Om[1])
2020 Sort the output from `ls \-l' by file size:
2025 Find most recent file in a directory:
2027 $ setopt dotglob ; print directory/**/*(om[1])
2030 List the top 100 biggest files in a disk
2032 $ zmodload \-i zsh/stat ; ls \-fld ./**/*(d`stat +device .`OL[1,100])
2038 Find all files without a valid owner:
2040 $ chmod someuser /**/*(D^u:${(j.:u:.)${(f)"$(</etc/passwd)"}%%:*}:)
2043 Show only files are owned from group `users':
2050 ``autoload zmv'' needed! See ``man zshcontrib | less -p zmv'' for more
2053 Serially all files (foo.foo > 1.foo, fnord.foo > 2.foo, ..):
2056 1.c asd.foo bla.foo fnord.foo foo.fnord foo.foo
2057 $ c=1 zmv '*.foo' '$((c++)).foo'
2059 1.c 1.foo 2.foo 3.foo 4.foo foo.fnord
2062 See above, but now only files with a filename >= 30 chars:
2064 $ c=1 zmv "${(l:30-4::?:)}*.foo" '$((c++)).foo'
2067 Replace spaces in filenames with a underline:
2069 $ zmv '* *' '$f:gs/ /_'
2072 Change the suffix from *.sh to *.pl:
2074 $ zmv -W '*.sh' '*.pl'
2077 lowercase/uppercase all files/directories:
2080 $ zmv '(*)' '${(L)1}'
2085 Remove the suffix *.c from all C-Files:
2090 Uppercase only the first letter of all *.mp3 - files:
2092 $ zmv '([a-z])(*).mp3' '${(C)1}$2.mp3'
2095 Copy the target `README' in same directory as each `Makefile':
2097 $ zmv -C '(**/)Makefile' '${1}README'
2100 Removing single quote from filenames (recursive):
2102 $ zmv -Q "(**/)(*'*)(D)" "\\$1\\${2//'/}"
2105 Replace spaces with underscores in filenames (recursive):
2107 $ zmv -Q "(**/)(* *)(D)" "\\$1\\${2// /_}"
2110 Rename pic1.jpg, pic2.jpg, .. to pic0001.jpg, pic0002.jpg, ..:
2113 $ zmv 'pic(*).jpg' 'pic${(l:4::0:)1}.jpg'
2115 $ zmv '(**/)pic(*).jpg' '$1/pic${(l:4::0:)2}.jpg'
2117 .SS TIPS BY ZZAPPER (http://www.rayninfo.co.uk/tips/zshtips.html)
2123 !$:h (last argument, strip one level)
2125 vi !* (all parameters)
2126 vi !$ (last parameters)
2129 ^fred^joe # edit previous command replace fred by joe
2133 cmdy !?cmd1?:*<TAB> #get parameters of a previous command
2136 !:0 is the previous command name
2137 !^, !:2, !:3, ?, !$ are the arguments
2138 !* is all the arguments
2139 !-2, !-3, ? are earlier commands
2140 !-2^, !-2:2, !-2$, !-2*
2142 cd !$:h (remove file name)
2143 cat !!:t (only file name)
2144 print ${param:&} (last substitute)
2147 # globbing modifiers
2148 # :r removes the suffix from the result,
2149 # :t takes away the directory part
2150 # . means must be regular files not directories etc
2151 # *(om[1]) picks most recently modified file
2152 # (.N) no warning message if any file absent
2153 print *(om[1]) # print the most recent file
2154 print *(.om[1]) # print the most recent file (not directory)
2155 ls -l *(Om[1]) # oldest file
2156 print *(om[1,5]) # print the 5 most recent files
2157 vi *(.om[1]^D) # vi newest file ^D means switch off GLOB_DOTS
2158 ls -l *(m4) # list files modified exactly 4 days ago
2159 ls -ltd *(mw3) # list files 3 weeks old
2160 echo *(m-1) # files modified today
2161 echo *(m0) # files modified today
2162 rm *.{aux,dvi,log,toc}(.N) # rm latex temp files N means no error msg is any file absent
2164 print *(n:t) # order by name strip directory
2165 print **/*(On:t) # recursive reverse order by name, strip directory
2166 print *.c(:r) # strip suffix
2167 ls **/*(.) # only files no directories
2168 -ld *(/) # list only directories
2169 FOO = (#i)foo ]] # case insensitive matching
2171 fred=$((6**2 + 6)) # can do maths
2172 print ${#path} # length of "path" array
2173 print ${#path[1]} # length of first element in path array
2178 array=(~/.zshenv ~/.zshrc ~/.zlogout)
2180 .zshenv .zshrc .zlogout
2182 x="bu&^*ck" # variable with mucky characters
2183 print ${x//[^[:alnum:]]/_} # replace all non-alphanumerics with _
2186 cp file ~1 # where 1 is first entry in pushd stack
2188 startfilename<tab> # will complete matching files anywhere in $PATH
2189 startfilename<C-D> # will list matching files anywhere in $PATH
2193 ls * | grep foo | less
2199 vim =some_file # edits file anywhere in $PATH
2200 ls =some_file # lists file anywhere in $PATH
2201 #magic ** (recursion)
2202 vim **/some_file # edits file under under current dir
2203 # modifying more than one file (multios)
2204 # writes ls results to file1 & file2 appends to filec
2205 ls > file1 > file2 >> file3 | wc
2207 .\"#######################################################
2209 .\"#######################################################
2211 Find file containing string 'printf' in /usr/include.
2213 $ zargs /usr/include/**/*.h \-\- grep printf /dev/null
2217 A solution without zsh could look like:
2219 $ find /usr/include -name \\*.h \-exec grep printf /dev/null {} \;
2223 Create a directory structure based on an existing one.
2226 $ cd \-\- $dest_root
2227 $ mkdir \-p \-\- $dirs
2231 A solution without zsh could look like:
2236 $ find . -type d | cpio -pdmv "$dst"
2240 Uncompress file and read it
2242 less <(gzip -cd foo.gz)
2246 A solution without zsh could look like:
2248 $ gzip -cd foo.gz && less foo
2252 Print two files and sort them
2258 A solution without zsh could look like:
2260 $ cat foo fubar | sort
2264 Find files up from current directory and change permissions
2271 A solution without zsh could look like:
2273 $ find . \-type f \-exec chmod 700 {} \\;
2277 List details of the executable 'foobar'.
2283 A solution without zsh could look like:
2285 $ ls -l `which foobar`
2288 .\"#######################################################
2292 \'cd old new' replaces 'old' with 'new' in directory-names.
2293 \'which -a cmd' lists all occurences of 'cmd' in $PATH.
2296 .\"#######################################################
2301 auto_cd (allow one to change to a directory by entering it as a command).
2302 auto_pushd (automatically append dirs to the push/pop list)
2303 pushd_ignore_dups (and don't duplicate them)
2308 no_hup (don't send HUP signal to background jobs when exiting ZSH)
2309 print_exit_value (show a message with the exit code when a command returns with a non-zero exit code)
2314 hist_verify (let the user edit the command line after history expansion (e.g. !ls) instead of immediately running it)
2317 Use the same history file for all sessions :
2319 setopt SHARE_HISTORY
2325 no_clobber (or set -C; prevent '>' redirection from truncating the given file if it already exists)
2330 correct (automatically correct the spelling of commands)
2331 correct_all (automatically correct the spelling of each word on the command line)
2332 dvorak (dvorak layout)
2333 .\"#######################################################
2335 .\"#######################################################
2338 The Z shell Homepage
2339 .B http://www.zsh.org/
2342 .B http://zsh.sunsite.dk/FAQ/
2345 .B http://www.zshwiki.org/
2348 .B http://www.zsh.org/mla/
2350 The Z shell reference-card (included in the zsh-lovers
2352 .B http://zsh.sunsite.dk/Refcard/refcard.ps.gz
2354 Adam Spier's UNIX shells page
2355 .B http://adamspiers.org/computing/shells/
2357 The Single UNIX (R) Specification, Version 2 - Shell Command Language Index
2358 .B http://www.opengroup.org/onlinepubs/007908799/xcu/shellix.html
2360 Zzappers Best of ZSH Tips
2361 .B http://www.rayninfo.co.uk/tips/zshtips.html
2363 The ZSH area on dotfiles.com
2364 .B http://www.dotfiles.com/index.php3?app_id=4
2366 Zsh Webpage by Christian Schneider
2367 .B http://strcat.neessen.net/zsh/
2369 The zsh-lovers webpage
2370 .B http://grml.org/zsh/
2374 #zsh at irc.freenode.org
2376 This manpage was written by Michael Prokop, Christian
2377 \'strcat' Schneider and Matthias Kopfermann. But many ideas
2378 have been taken from zsh-geeks e.g. from the
2379 zsh-mailinglists (zsh-users and zsh-workers), google,
2380 newsgroups and the zsh-Wiki. Thanks for your cool and
2381 incredible tips. We learned much from you!
2383 In alphabetic order:
2385 Andrew 'zefram' Main - http://www.fysh.org/~zefram/
2386 Barton E. Schaefer - http://www.well.com/user/barts/
2387 Matthias Kopfermann - http://www.infodrom.north.de/~matthi/
2388 Oliver Kiddle - http://people.freenet.de/opk/
2389 Paul Falstad - http://www.falstad.com/
2390 Peter Stephenson - http://python.swan.ac.uk/~pypeters/
2392 Stephane Chazelas - http://stephane.chazelas.free.fr/
2393 Sven Guckes - http://www.guckes.net/
2394 Sven Wischnowsky - http://w9y.de/zsh/zshrc
2400 zsh Zsh overview (this section)
2401 zshmisc Anything not fitting into the other sections
2402 zshexpn Zsh command and parameter expansion
2403 zshparam Zsh parameters
2404 zshoptions Zsh options
2405 zshbuiltins Zsh built-in functions
2406 zshzle Zsh command line editing
2407 zshcompwid Zsh completion widgets
2408 zshcompsys Zsh completion system
2409 zshcompctl Zsh completion control
2410 zshmodules Zsh loadable modules
2411 zshzftpsys Zsh built-in FTP client
2412 zshall Meta-man page containing all of the above
2414 Note: especially 'man zshcontrib' covers very useful topics!
2418 From Bash to Z Shell
2419 by Oliver Kiddle, Jerry Peck and Peter Stephenson
2422 Also take a look at the section
2427 Probably. This manpage might be never complete.
2428 So please report bugs, feedback and suggestions to
2429 <zsh-lovers@michael-prokop.at>. Thank you!
2432 Copyright \(co 2005 Michael Prokop, Christian Schneider and Matthias Kopfermann.
2433 .\"###### END OF FILE ##########################################################