Aller au contenu

zsh

The Z Shell Manual

Fichiers de configurations:

  • ~/.zshenv : contient les variables de l'environnement
  • ~/.zshrc : contient les aliases, les options (setopt), les fonctions, les zstyles…
  • ~/.zlogin : contient des commandes executées aprés le login.
  • ~/.zlogout : contient des commandes executées lors de la fermeture logout.
Ordre de chargement:

/etc/zshenv ➔ ~/.zshenv

/etc/zprofile ➔ ~/.zprofile (login shell)

/etc/zshrc ➔ ~/.zshrc (interactive shell)

/etc/zlogin ➔ ~/.zlogin

~/.zlogout ➔ /etc/zlogout

La variable ZDOTDIR définit l'endroit où se trouve les fichiers de configuration (~/ par défaut). Elle se définit dans ~/.zshenv

Options:

http://zsh.sourceforge.net/Doc/Release/Options.html#Options

Voir les options:

$ setopt
alwaystoend
autocd
combiningchars
correctall
extendedhistory
histignorealldups
histreduceblanks
incappendhistory
interactive
login
monitor
nopromptcr
promptsubst
sharehistory
shinstdin
zle

Toutes les options par défaut:

$ emulate -lLR zsh
setopt NO_CASE_GLOB
setopt AUTO_CD

# add a timestamp
setopt EXTENDED_HISTORY
# size
SAVEHIST=5000
HISTSIZE=2000
# share history across multiple zsh sessions
setopt SHARE_HISTORY
# append to history
setopt APPEND_HISTORY
# adds commands as they are typed, not at shell exit
setopt INC_APPEND_HISTORY
# expire duplicates first
setopt HIST_EXPIRE_DUPS_FIRST 
# do not store duplications
setopt HIST_IGNORE_DUPS
#ignore duplicates when searching
setopt HIST_FIND_NO_DUPS
# removes blank lines from history
setopt HIST_REDUCE_BLANKS

setopt HIST_VERIFY

setopt CORRECT
setopt CORRECT_ALL

Remettre les options par défaut:

$ emulate -LR zsh

Ré-entrer la dernière commande:

$ du -schx * | sort -nr
924K    Regular-Expressions.pdf
...

$ !!
du -schx * | sort -nr
924K    Regular-Expressions.pdf

$ cd ; !!
cd ; du -schx * | sort -nr

Très utile quand on a oublié le sudo:

$ apachectl -k restart
httpd not running, trying to start
(13)Permission denied: AH00091: httpd: could not open error log file /usr/local/var/log/httpd/error_log.
AH00015: Unable to open logs

$ sudo !!
sudo apachectl -k restart
Password:
httpd not running, trying to start

# L'option  HIST_VERIFY permet de vérifier la commande avant de l'exécuter

Globbing

# list every file directly below the zsh_demo folder
ls zsh_demo

# list every file in the folders directly below the zsh_demo folder
ls zsh_demo/*

# list every file in every folder two levels below the zsh_demo folder
ls zsh_demo/*/*

# list every file anywhere below the zsh_demo folder
ls zsh_demo/**/*

# list every file that ends in .txt in every folder at any level below the zsh_demo folder
ls zsh_demo/**/*.txt

Glob operators

# list text files that end in a number from 1 to 10
ls -l zsh_demo/**/*<1-10>.txt

# list text files that start with the letter a
ls -l zsh_demo/**/[a]*.txt

# list text files that start with either ab or bc
ls -l zsh_demo/**/(ab|bc)*.txt

# list text files that don't start with a lower or uppercase c
ls -l zsh_demo/**/[^cC]*.txt

Glob qualifiers

# show only directories
print -l zsh_demo/**/*(/)

# show only regular files
print -l zsh_demo/**/*(.)

# show empty files
ls -l zsh_demo/**/*(L0)

# show files greater than 3 KB
ls -l zsh_demo/**/*(Lk+3)

# show files modified in the last hour
print -l zsh_demo/**/*(mh-1)

# sort files from most to least recently modified and show the last 3
ls -l zsh_demo/**/*(om[1,3])

Modifiers

# A plain old glob
print -l zsh_demo/data/europe/poland/*.txt

# Return the file name (t stands for tail)
print -l zsh_demo/data/europe/poland/*.txt(:t)

# Return the file name without the extension (r stands for remove_extension, I think)
print -l zsh_demo/data/europe/poland/*.txt(:t:r)

# Return the extension
print -l zsh_demo/data/europe/poland/*.txt(:e)

# Return the parent folder of the file (h stands for head)
print -l zsh_demo/data/europe/poland/*.txt(:h)

# Return the parent folder of the parent
print -l zsh_demo/data/europe/poland/*.txt(:h:h)

# Return the parent folder of the first file
print -l zsh_demo/data/europe/poland/*.txt([1]:h)
# Remember you can combine qualifiers and modifiers.

ZLE

ZLE désigne la zone dans laquelle vous tapez vos commandes. Vous pouvez utiliser les raccourcis claviers de vi ou d'emacs, au choix, et définir très facilement vos propres raccourcis. En vrac, quelques raccourcis par défaut :

  • h va appeler la page de manuel du premier mot que vous êtes en train de taper
  • q va copier la ligne que vous étiez en train de taper en mémoire, pour vous laisser devant une ligne vide. Vous pouvez alors rentrer une nouvelle commande, lorsque celle-ci sera terminée, zsh vous affichera la ligne en mémoire.

Fonctions autoload

Au lieu de déclarer la fonction directement le fichier de configuration, vous pouvez placer la fonction dans un fichier séparé. zsh a une variable intégrée appelée fpath qui est un tableau de chemins où zsh recherchera les fichiers définissant une fonction. Vous pouvez ajouter votre propre répertoire à ce chemin de recherche:

fpath+=~/Documents/zshfunctions

Il faut aussi dire à zsh que vous souhaitez utilisez cette fonction:

autoload my_ps
~/Documents/zshfunctions master*
❯ l
total 4
-rw-r--r-- 1 bruno staff 61 déc 10 17:48 my_ps
# my_ps file

ps $@ -u $USER -o pid,%cpu,%mem,start,time,bsdtime,command ;

https://scriptingosx.com/2019/07/moving-to-zsh-part-4-aliases-and-functions/

Alias suffixes

alias -s tex=vim
alias -s html=w3m
alias -s org=w3m

Now pressing return-key after entering foobar.tex starts vim with foobar.tex. Calling a html-file runs browser w3m. www.zsh.org and pressing enter starts w3m with argument www.zsh.org.

Alias globaux

Zsh permet également de définir des alias "globaux" qui s’exécuteront quelle que soit leur position dans la ligne de commande, ainsi:

 alias -g G=' | grep '

remplacera la commande

 ls /bin G zsh

par

 ls /bin | grep zsh
 alias -g G='| wc -l'

remplacera la commande

 grep alias ~/.zshrc C

par

 grep alias ~/.zshrc | wc -l
alias -g ...='../..'
alias -g ....='../../..'
alias -g .....='../../../..'

alias -g C='| wc -l'

alias -g DN=/dev/null

alias -g H='| head'

alias -g LL="2>&1 | less"
alias -g L="| less"
alias -g LS='| less -S'

alias -g NE="2> /dev/null"
alias -g NUL="> /dev/null 2>&1"

alias -g NS='| sort -n'
alias -g RNS='| sort -nr'
alias -g S='| sort'
alias -g US='| sort -u'

alias -g TL='| tail -20'
alias -g T='| tail'

alias -g X='| xargs'

which:

which fonctionne aussi pour les alias:

$ which l
l: aliased to gls -lA --color

$ which 'NUL'
NUL: globally aliased to > /dev/null 2>&1

Raccourcis:

ESC - H: Affiche le MAN d'une commande

bookmarks:

how-to-use-bookmarks-in-bash-zsh

Ajouter au .zshrc

if [ -d "$HOME/.bookmarks" ]; then
    export CDPATH=".:$HOME/.bookmarks:/"
    alias goto="cd -P"
fi

Créer le dossier .bookmarks

mkdir ~/.bookmarks

Ajouter les bookmarks:

~/.bookmarks                                                                             
$ ln -s /Users/bruno/Documents/MySQL @MySQL_backup

~/.bookmarks                                                                        
$ ln -s $(brew --prefix)/var/mysql @MySQL_databases

Utilisation:

$ goto @<Tab>
@MySQL_backup@     @MySQL_databases@  @kymsu@            @kymsu_git@        @scripts_bash@

Pour bash

http://grml.org/zsh/zsh-lovers.html


Dernière mise à jour: September 15, 2021