Difference between revisions of "Zsh"

From ArchWiki
Jump to navigation Jump to search
m (→‎xterm title: add prompt symbol)
(Change the "Type" field of zsh.hook to "Path", Because the "target" field of "Package" can only be the package name.)
 
(202 intermediate revisions by 31 users not shown)
Line 8: Line 8:
 
[[ru:Zsh]]
 
[[ru:Zsh]]
 
[[zh-hans:Zsh]]
 
[[zh-hans:Zsh]]
[http://zsh.sourceforge.net/Intro/intro_1.html Zsh] is a powerful [[shell]] that operates as both an interactive shell and as a scripting language interpreter. While being compatible with [[Bash]] (not by default, only if issuing {{ic|emulate sh}}), it offers advantages such as improved [http://zsh.sourceforge.net/Guide/zshguide06.html tab completion] and [http://zsh.sourceforge.net/Doc/Release/Expansion.html globbing].
+
[https://www.zsh.org/ Zsh] is a powerful [[shell]] that operates as both an interactive shell and as a scripting language interpreter. While being compatible with the POSIX sh (not by default, only if issuing {{ic|emulate sh}}), it offers advantages such as improved [http://zsh.sourceforge.net/Guide/zshguide06.html tab completion] and [http://zsh.sourceforge.net/Doc/Release/Expansion.html globbing].
  
 
The [http://zsh.sourceforge.net/FAQ/zshfaq01.html#l4 Zsh FAQ] offers more reasons to use Zsh.
 
The [http://zsh.sourceforge.net/FAQ/zshfaq01.html#l4 Zsh FAQ] offers more reasons to use Zsh.
Line 14: Line 14:
 
== Installation ==
 
== Installation ==
  
Before starting users may want to see what shell is currently being used:
+
Before starting, users may want to see what shell is currently being used:
  
 
  $ echo $SHELL
 
  $ echo $SHELL
Line 26: Line 26:
 
  $ zsh
 
  $ zsh
  
You should now see ''zsh-newuser-install'', which will walk you through some basic configuration. If you want to skip this, press {{ic|q}}. If you did not see it, you can invoke it manually with
+
You should now see ''zsh-newuser-install'', which will walk you through some basic configuration. If you want to skip this, press {{ic|q}}. If you did not see it, you can invoke it manually with:
  
  $ zsh /usr/share/zsh/functions/Newuser/zsh-newuser-install -f
+
  $ autoload -Uz zsh-newuser-install
 +
$ zsh-newuser-install -f
 +
 
 +
{{Note|Make sure your terminal's size is at least 72×15 otherwise ''zsh-newuser-install'' will not run.}}
  
 
=== Making Zsh your default shell ===
 
=== Making Zsh your default shell ===
  
See [[Command-line shell#Changing your default shell]].
+
Change your shell to {{ic|/usr/bin/zsh}}. See [[Command-line shell#Changing your default shell]].
  
{{Tip|If replacing {{Pkg|bash}}, users may want to move some code from {{ic|~/.bashrc}} to {{ic|~/.zshrc}} (e.g. the prompt and the [[Bash#Aliases|aliases]]) and from {{ic|~/.bash_profile}} to {{ic|~/.zprofile}} (e.g. [[xinitrc#Autostart X at login|the code that starts the X Window System]]).}}
+
{{Tip|If replacing {{Pkg|bash}}, users may want to move some code from {{ic|~/.bashrc}} to {{ic|~/.zshrc}} (e.g. the prompt and the [[Bash#Aliases|aliases]]) and from {{ic|~/.bash_profile}} to {{ic|~/.zprofile}} (e.g. [[xinit#Autostart X at login|the code that starts the X Window System]]).}}
  
 
== Startup/Shutdown files ==
 
== Startup/Shutdown files ==
  
{{Tip|See [http://zsh.sourceforge.net/Guide/zshguide02.html A User's Guide to the Z-Shell] for explanation on interactive and login shells, and what to put in your startup files.}}
+
{{Tip|
 +
* See [http://zsh.sourceforge.net/Guide/zshguide02.html A User's Guide to the Z-Shell] for explanation on interactive and login shells, and what to put in your startup files.
 +
* You could consider [[Command-line shell#Standardisation|implementing a standard path]] for your Zsh configuration files.
 +
}}
  
 
{{Note|
 
{{Note|
 
* If {{ic|$ZDOTDIR}} is not set, {{ic|$HOME}} is used instead.
 
* If {{ic|$ZDOTDIR}} is not set, {{ic|$HOME}} is used instead.
* If option {{ic|RCS}} is unset in any of the files, no configuration files will be sourced after that file.
+
* If option {{ic|RCS}} is unset in any of the files, no configuration files will be read after that file.
* If option {{ic|GLOBAL_RCS}} is unset in any of the files, no global configuration files ({{ic|/etc/zsh/*}}) will be sourced after that file.
+
* If option {{ic|GLOBAL_RCS}} is unset in any of the files, no global configuration files ({{ic|/etc/zsh/*}}) will be read after that file.
 
}}
 
}}
  
When starting Zsh, it will source the following files in this order by default:
+
When starting, Zsh will read commands from the following files in this order by default:
  
* {{ic|/etc/zsh/zshenv}} Used for setting system-wide [[environment variables]]; it should not contain commands that produce output or assume the shell is attached to a tty. This file will '''''always''''' be sourced, this cannot be overridden.
+
* {{ic|/etc/zsh/zshenv}} Used for setting [[environment variables]] for all users; it should not contain commands that produce output or assume the shell is attached to a TTY. This file will '''''always''''' be read, this cannot be overridden.
* {{ic|$ZDOTDIR/.zshenv}} Used for setting user's environment variables; it should not contain commands that produce output or assume the shell is attached to a tty. This file will '''''always''''' be sourced.
+
* {{ic|$ZDOTDIR/.zshenv}} Used for setting user's environment variables; it should not contain commands that produce output or assume the shell is attached to a TTY. This file will '''''always''''' be read.
* {{ic|/etc/zsh/zprofile}} Used for executing commands at start, will be sourced when starting as a '''''login shell'''''. Please note that on Arch Linux, by default it contains [https://projects.archlinux.org/svntogit/packages.git/tree/trunk/zprofile?h=packages/zsh one line] which source the {{ic|/etc/profile}}.
+
* {{ic|/etc/zsh/zprofile}} Used for executing commands at start for all users, will be read when starting as a '''''login shell'''''. Please note that on Arch Linux, by default it contains [https://projects.archlinux.org/svntogit/packages.git/tree/trunk/zprofile?h=packages/zsh one line] which source the {{ic|/etc/profile}}. See warning below before wanting to remove that!
** {{ic|/etc/profile}} This file should be sourced by all Bourne-compatible shells upon login: it sets up {{ic|$PATH}} and other environment variables and application-specific ({{ic|/etc/profile.d/*.sh}}) settings upon login.
+
** {{ic|/etc/profile}} This file should be sourced by all POSIX sh-compatible shells upon login: it sets up {{ic|$PATH}} and other environment variables and application-specific ({{ic|/etc/profile.d/*.sh}}) settings upon login.
* {{ic|$ZDOTDIR/.zprofile}} Used for executing user's commands at start, will be sourced when starting as a '''''login shell'''''.
+
* {{ic|$ZDOTDIR/.zprofile}} Used for executing user's commands at start, will be read when starting as a '''''login shell'''''. Typically used to autostart graphical sessions and to set session-wide environment variables.
* {{ic|/etc/zsh/zshrc}} Used for setting interactive shell configuration and executing commands, will be sourced when starting as an '''''interactive shell'''''.
+
* {{ic|/etc/zsh/zshrc}} Used for setting interactive shell configuration and executing commands for all users, will be read when starting as an '''''interactive shell'''''.
* {{ic|$ZDOTDIR/.zshrc}} Used for setting user's interactive shell configuration and executing commands, will be sourced when starting as an '''''interactive shell'''''.
+
* {{ic|$ZDOTDIR/.zshrc}} Used for setting user's interactive shell configuration and executing commands, will be read when starting as an '''''interactive shell'''''.
* {{ic|/etc/zsh/zlogin}} Used for executing commands at ending of initial progress, will be sourced when starting as a '''''login shell'''''.
+
* {{ic|/etc/zsh/zlogin}} Used for executing commands for all users at ending of initial progress, will be read when starting as a '''''login shell'''''.
* {{ic|$ZDOTDIR/.zlogin}} Used for executing user's commands at ending of initial progress, will be sourced when starting as a '''''login shell'''''.
+
* {{ic|$ZDOTDIR/.zlogin}} Used for executing user's commands at ending of initial progress, will be read when starting as a '''''login shell'''''. Typically used to autostart command line utilities. Should not be used to autostart graphical sessions, as at this point the session might contain configuration meant only for an interactive shell.
* {{ic|$ZDOTDIR/.zlogout}} Will be sourced when a '''''login shell''''' '''exits'''.
+
* {{ic|$ZDOTDIR/.zlogout}} Used for executing commands when a '''''login shell''''' '''exits'''.
* {{ic|/etc/zsh/zlogout}} Will be sourced when a '''''login shell''''' '''exits'''.
+
* {{ic|/etc/zsh/zlogout}} Used for executing commands for all users when a '''''login shell''''' '''exits'''.
 +
 
 +
See [https://blog.flowblok.id.au/2013-02/shell-startup-scripts.html#implementation the graphic representation].
  
 
{{Note|
 
{{Note|
 +
* {{ic|$HOME/.profile}} is not a part of the Zsh startup files and '''is not sourced''' by Zsh unless Zsh is invoked as {{ic|sh}} or {{ic|ksh}} and started as a login shell. For more details about the sh and ksh compatibility modes refer to {{man|1|zsh|COMPATIBILITY}}.
 
* The paths used in Arch's {{Pkg|zsh}} package are different from the default ones used in the [[man page]]s ({{Bug|48992}}).
 
* The paths used in Arch's {{Pkg|zsh}} package are different from the default ones used in the [[man page]]s ({{Bug|48992}}).
* {{ic|/etc/profile}} is not a part of the regular list of startup files run for Zsh, but is sourced from {{ic|/etc/zsh/zprofile}} in the {{Pkg|zsh}} package. Users should take note that {{ic|/etc/profile}} sets the {{ic|$PATH}} variable which will overwrite any {{ic|$PATH}} variable set in {{ic|$ZDOTDIR/.zshenv}}. To prevent this, please [[#Configuring $PATH|set the {{ic|$PATH}} variable]] in {{ic|$ZDOTDIR/.zprofile}}.
 
 
}}
 
}}
  
{{Warning|It is not recommended to replace the default [https://projects.archlinux.org/svntogit/packages.git/tree/trunk/zprofile?h=packages/zsh one line] in {{ic|/etc/zsh/zprofile}} with something other, it will break the integrality of other packages which provide some scripts in {{ic|/etc/profile.d/}}.}}
+
{{Warning|Do not remove the default [https://projects.archlinux.org/svntogit/packages.git/tree/trunk/zprofile?h=packages/zsh one line] in {{ic|/etc/zsh/zprofile}}, otherwise it will break the integrity of other packages which provide some scripts in {{ic|/etc/profile.d/}}.}}
  
 
== Configure Zsh ==
 
== Configure Zsh ==
Line 90: Line 98:
 
=== Configuring $PATH ===
 
=== Configuring $PATH ===
  
Normally, the path should be set in {{ic|~/.zshenv}}, but Arch Linux sources {{ic|/etc/profile}} after sourcing {{ic|~/.zshenv}}.
+
Zsh ties the {{ic|PATH}} variable to an {{ic|path}} array. They are automatically synchronized. This allows us to easily manipulate {{ic|PATH}} by simply modifying the array. See [http://zsh.sourceforge.net/Guide/zshguide02.html#l24 A User's Guide to the Z-Shell] for details.
  
To prevent your {{ic|$PATH}} being overwritten, set it in {{ic|~/.zprofile}}.
+
The line {{ic|typeset -U PATH path}}, where the {{ic|-U}} stands for unique, instructs the shell to discard duplicates from both {{ic|$PATH}} and {{ic|$path}}:
  
{{hc|~/.zprofile|2=
+
{{hc|~/.zshenv|2=
typeset -U path
+
typeset -U PATH path
path=(''~/bin'' ''/other/things/in/path'' $path[@])
+
path=("$HOME/.local/bin" ''/other/things/in/path'' "$path[@]")
 +
export PATH
 
}}
 
}}
 
See also [http://zsh.sourceforge.net/Guide/zshguide02.html#l24 A User's Guide to the Z-Shell] and the note in [[#Startup/Shutdown files]].
 
  
 
=== Command completion ===
 
=== Command completion ===
Line 110: Line 117:
 
}}
 
}}
  
The above configuration includes ssh/scp/sftp hostnames completion but in order for this feature to work, users need to prevent ssh from hashing hosts names in {{ic|~/.ssh/known_hosts}}.
+
The above configuration includes ssh/scp/sftp hostnames completion but in order for this feature to work, users must not enable ssh's hostname hashing (i.e. option {{ic|HashKnownHosts}} in ssh client configuration).
 
 
{{Warning|This makes the computer vulnerable to [http://blog.rootshell.be/2010/11/03/bruteforcing-ssh-known_hosts-files/ "Island-hopping" attacks]. In that intention, comment the following line or set the value to {{ıc|no}}:
 
 
 
{{hc|/etc/ssh/ssh_config|
 
#HashKnownHosts yes
 
}}
 
 
 
And move {{ic|~/.ssh/known_hosts}} somewhere else so that ssh creates a new one with un-hashed hostnames (previously known hosts will thus be lost). For more information, see the SSH readme for [http://nms.lcs.mit.edu/projects/ssh/README.hashed-hosts hashed-hosts].
 
}}
 
  
 
For autocompletion with an arrow-key driven interface, add the following to:
 
For autocompletion with an arrow-key driven interface, add the following to:
Line 127: Line 125:
 
}}
 
}}
  
:''To activate the menu, press tab twice.''
+
To activate the menu, press {{ic|Tab}} twice.
  
 
For autocompletion of command line switches for aliases, add the following to:
 
For autocompletion of command line switches for aliases, add the following to:
Line 134: Line 132:
 
setopt COMPLETE_ALIASES
 
setopt COMPLETE_ALIASES
 
}}
 
}}
+
 
 +
For enabling autocompletion of privileged environments in privileged commands (e.g. if you complete a command starting with [[sudo]], completion scripts will also try to determine your completions with sudo), include:
 +
 
 +
{{hc|~/.zshrc|
 +
zstyle ':completion::complete:*' gain-privileges 1
 +
}}
 +
 
 +
{{Warning|This will let Zsh completion scripts run commands with sudo privileges. You should not enable this if you use untrusted autocompletion scripts.}}
 +
 
 +
{{Note|This special kind of context-aware completion is only available for a small number of commands.}}
 +
 
 
=== Key bindings ===
 
=== Key bindings ===
  
Zsh does not use [[readline]], instead it uses its own and more powerful Zsh Line Editor, ZLE. It does not read {{ic|/etc/inputrc}} or {{ic|~/.inputrc}}.
+
Zsh does not use [[readline]], instead it uses its own and more powerful Zsh Line Editor (ZLE). It does not read {{ic|/etc/inputrc}} or {{ic|~/.inputrc}}. Read [https://sgeb.io/posts/2014/04/zsh-zle-custom-widgets/ A closer look at the zsh line editor and creating custom widgets] for an introduction to ZLE configuration.
ZLE has an [[emacs]] mode and a [[vi]] mode. If one of the {{ic|$VISUAL}} or {{ic|$EDITOR}} environment variables contain the string {{ic|vi}} then vi mode will be used; otherwise, it will default to emacs mode. Set the mode explicitly with {{ic|bindkey -e}} or {{ic|bindkey -v}} respectively for emacs mode or vi mode.
+
 
 +
ZLE has an [[Emacs]] mode and a [[vi]] mode. If one of the {{ic|VISUAL}} or {{ic|EDITOR}} [[environment variables]] contain the string {{ic|vi}} then vi mode will be used; otherwise, it will default to Emacs mode. Set the mode explicitly with {{ic|bindkey -e}} or {{ic|bindkey -v}} respectively for Emacs mode or vi mode.
 +
 
 +
Key bindings are assigned by mapping an escape sequence matching a keypress to a ZLE widget. The available widgets, with descriptions of their actions and their default keybindings, are listed in {{man|1|zshzle|STANDARD WIDGETS}} and {{man|1|zshcontrib|ZLE FUNCTIONS}}.
 +
 
 +
The recommended way to set key bindings in Zsh is by using string capabilities from {{man|5|terminfo}}. For example[https://web.archive.org/web/20180704181216/http://zshwiki.org/home/zle/bindkeys][https://www.zsh.org/mla/users/2010/msg00065.html]:
 +
 
 +
{{hc|~/.zshrc|2=
 +
# create a zkbd compatible hash;
 +
# to add other keys to this hash, see: man 5 terminfo
 +
typeset -g -A key
 +
 
 +
key[Home]="${terminfo[khome]}"
 +
key[End]="${terminfo[kend]}"
 +
key[Insert]="${terminfo[kich1]}"
 +
key[Backspace]="${terminfo[kbs]}"
 +
key[Delete]="${terminfo[kdch1]}"
 +
key[Up]="${terminfo[kcuu1]}"
 +
key[Down]="${terminfo[kcud1]}"
 +
key[Left]="${terminfo[kcub1]}"
 +
key[Right]="${terminfo[kcuf1]}"
 +
key[PageUp]="${terminfo[kpp]}"
 +
key[PageDown]="${terminfo[knp]}"
 +
key[Shift-Tab]="${terminfo[kcbt]}"
 +
 
 +
# setup key accordingly
 +
[[ -n "${key[Home]}"      ]] && bindkey -- "${key[Home]}"      beginning-of-line
 +
[[ -n "${key[End]}"      ]] && bindkey -- "${key[End]}"      end-of-line
 +
[[ -n "${key[Insert]}"    ]] && bindkey -- "${key[Insert]}"    overwrite-mode
 +
[[ -n "${key[Backspace]}" ]] && bindkey -- "${key[Backspace]}" backward-delete-char
 +
[[ -n "${key[Delete]}"    ]] && bindkey -- "${key[Delete]}"    delete-char
 +
[[ -n "${key[Up]}"        ]] && bindkey -- "${key[Up]}"        up-line-or-history
 +
[[ -n "${key[Down]}"      ]] && bindkey -- "${key[Down]}"      down-line-or-history
 +
[[ -n "${key[Left]}"      ]] && bindkey -- "${key[Left]}"      backward-char
 +
[[ -n "${key[Right]}"    ]] && bindkey -- "${key[Right]}"    forward-char
 +
[[ -n "${key[PageUp]}"    ]] && bindkey -- "${key[PageUp]}"    beginning-of-buffer-or-history
 +
[[ -n "${key[PageDown]}"  ]] && bindkey -- "${key[PageDown]}"  end-of-buffer-or-history
 +
[[ -n "${key[Shift-Tab]}" ]] && bindkey -- "${key[Shift-Tab]}" reverse-menu-complete
 +
 
 +
# Finally, make sure the terminal is in application mode, when zle is
 +
# active. Only then are the values from $terminfo valid.
 +
if (( ${+terminfo[smkx]} && ${+terminfo[rmkx]} )); then
 +
autoload -Uz add-zle-hook-widget
 +
function zle_application_mode_start { echoti smkx }
 +
function zle_application_mode_stop { echoti rmkx }
 +
add-zle-hook-widget -Uz zle-line-init zle_application_mode_start
 +
add-zle-hook-widget -Uz zle-line-finish zle_application_mode_stop
 +
fi
 +
}}
  
See [http://zshwiki.org/home/zle/bindkeys ZshWiki: zle:bindkeys] for instructions on keybinding setup.
+
==== History search ====
  
=== History search ===
+
You need to set up the {{ic|key}} array and make sure that ZLE enters application mode to use the following instructions; see [[#Key bindings]].
  
You need to set up [[#Key bindings]] to use this. To enable history search add these lines to {{ic|.zshrc}} file:
+
To enable history search add these lines to {{ic|.zshrc}} file:
  
{{hc|~/.zshrc|<nowiki>
+
{{hc|~/.zshrc|
 
autoload -Uz up-line-or-beginning-search down-line-or-beginning-search
 
autoload -Uz up-line-or-beginning-search down-line-or-beginning-search
 
zle -N up-line-or-beginning-search
 
zle -N up-line-or-beginning-search
 
zle -N down-line-or-beginning-search
 
zle -N down-line-or-beginning-search
  
[[ -n "$key[Up]"  ]] && bindkey -- "$key[Up]"  up-line-or-beginning-search
+
[[ -n "${key[Up]}"  ]] && bindkey -- "${key[Up]}"  up-line-or-beginning-search
[[ -n "$key[Down]" ]] && bindkey -- "$key[Down]" down-line-or-beginning-search
+
[[ -n "${key[Down]}" ]] && bindkey -- "${key[Down]}" down-line-or-beginning-search
</nowiki>}}
+
}}
  
 
By doing this, only the past commands matching the current line up to the current cursor position will be shown when {{ic|Up}} or {{ic|Down}} keys are pressed.
 
By doing this, only the past commands matching the current line up to the current cursor position will be shown when {{ic|Up}} or {{ic|Down}} keys are pressed.
 +
 +
==== Shift, Alt, Ctrl and Meta modifiers ====
 +
 +
xterm-compatible terminals can use extended key-definitions from {{man|5|user_caps}}. Those are combinations of {{ic|Shift}}, {{ic|Alt}}, {{ic|Ctrl}} and {{ic|Meta}} together with {{ic|Up}}, {{ic|Down}}, {{ic|Left}}, {{ic|Right}}, {{ic|PageUp}}, {{ic|PageDown}}, {{ic|Home}}, {{ic|End}} or {{ic|Del}}.
 +
 +
For example, for {{ic|Ctrl+Left}} to move to the beginning of the previous word and {{ic|Ctrl+Right}} to move to the beginning of the next word:
 +
 +
{{hc|~/.zshrc|2=
 +
key[Control-Left]="${terminfo[kLFT5]}"
 +
key[Control-Right]="${terminfo[kRIT5]}"
 +
 +
[[ -n "${key[Control-Left]}"  ]] && bindkey -- "${key[Control-Left]}"  backward-word
 +
[[ -n "${key[Control-Right]}" ]] && bindkey -- "${key[Control-Right]}" forward-word
 +
}}
  
 
=== Prompts ===
 
=== Prompts ===
  
{{Note|Zsh introduced a bug in 5.3 with multi-line prompts. Tab completion will move your cursor up deleting a line of your prompt. See [https://www.zsh.org/mla/workers//2017/msg00021.html] for more details. For temporary workarounds you can either use Zsh 5.2, or attempt a number of workarounds listed [https://github.com/sorin-ionescu/prezto/issues/1245].}}
+
Zsh offers the options of using a prompt theme or, for users who are dissatisfied with the themes (or want to expand their usefulness), the possibility to build a custom prompt.
  
 
==== Prompt themes ====
 
==== Prompt themes ====
  
There is a quick and easy way to set up a colored prompt in Zsh. Make sure that prompt theme system is set to autoload in {{ic|.zshrc}}. This can be done by adding these lines to:
+
Prompt themes are a quick and easy way to set up a colored prompt in Zsh. See {{man|1|zshcontrib|PROMPT THEMES}} for more information about them.
 +
 
 +
To use a theme, make sure that prompt theme system is set to autoload in {{ic|.zshrc}}. This can be done by adding these lines to:
  
 
{{hc|~/.zshrc|
 
{{hc|~/.zshrc|
Line 181: Line 253:
  
 
  $ prompt -p
 
  $ prompt -p
 +
 +
===== Manually installing prompt themes =====
 +
 +
It is possible to install themes manually, without external configuration manager tools. For a local installation, first create a folder and add it to the {{ic|fpath}} array, eg:
 +
 +
$ mkdir ~/.zprompts
 +
$ fpath=("$HOME/.zprompts" "$fpath[@]")
 +
 +
Now create a symbolic link of your theme file in this folder:
 +
 +
$ ln -s mytheme.zsh ~/.zprompts/prompt_mytheme_setup
 +
 +
If instead you wish to install a theme globally, do:
 +
 +
# ln -s mytheme.zsh /usr/share/zsh/functions/Prompts/prompt_mytheme_setup
 +
 +
Now you should be able to activate it using:
 +
 +
$ prompt mytheme
 +
 +
If everything works, you can edit your {{ic|.zshrc}} accordingly.
  
 
==== Customized prompt ====
 
==== Customized prompt ====
  
For users who are dissatisfied with the prompts mentioned above (or want to expand their usefulness), Zsh offers the possibility to build a custom prompt. Zsh supports a left- and right-sided prompt additional to the single, left-sided prompt that is common to all shells. Customize it by using {{ic|1=PROMPT=}} with prompt escapes.
+
{{Expansion|Add a simple colorless {{ic|PROMPT}} example.}}
  
See [http://zsh.sourceforge.net/Doc/Release/Prompt-Expansion.html Prompt Expansion] for a list of prompt variables and conditional substrings, or take a look at the {{man|1|zshmisc}} manpage.
+
Additionally to a primary left-sided prompt {{ic|PS1}} ({{ic|PROMPT}}, {{ic|prompt}}) that is common to all shells, Zsh also supports a right-sided prompt {{ic|RPS1}} ({{ic|RPROMPT}}). These two variables are the ones you will want to set to a custom value.
 +
 
 +
Other special purpose prompts, such as {{ic|PS2}} ({{ic|PROMPT2}}), {{ic|PS3}} ({{ic|PROMPT3}}), {{ic|PS4}} ({{ic|PROMPT4}}), {{ic|RPS1}} ({{ic|RPROMPT}}), {{ic|RPS2}} ({{ic|RPROMPT2}}) and {{ic|SPROMPT}}, are explained in {{man|1|zshparam|PARAMETERS USED BY THE SHELL}}.
 +
 
 +
All prompts can be customized with prompt escapes. The available prompt escapes are listed in {{man|1|zshmisc|EXPANSION OF PROMPT SEQUENCES}}.
  
 
===== Colors =====
 
===== Colors =====
  
Zsh sets colors differently than [[Color_Bash_Prompt|Bash]].
+
Zsh sets colors differently than [[Bash/Prompt customization|Bash]], you do not need to use convoluted ANSI escape sequences or terminal capabilities from {{man|5|terminfo}}. Zsh provides convenient prompt escapes to set the foreground color, background color and other visual effects; see {{man|1|zshmisc|Visual effects}} for a list of them and their descriptions.
  
See [http://zsh.sourceforge.net/Doc/Release/Prompt-Expansion.html#Visual-effects Visual effects] in {{man|1|zshmisc}} for prompt escapes to set foreground color, background color and other visual effects.
+
[http://zsh.sourceforge.net/FAQ/zshfaq03.html#l42 Colors] can be specified using a decimal integer, the name of one of the eight most widely-supported colors or as a # followed by an RGB triplet in hexadecimal format. See the description of fg=colour in {{man|1|zshzle|CHARACTER HIGHLIGHTING}} for more details.
  
Colors can be specified by [https://upload.wikimedia.org/wikipedia/commons/1/15/Xterm_256color_chart.svg numeric color code] or by name (see {{man|1|zshzle}} section [http://zsh.sourceforge.net/Doc/Release/Zsh-Line-Editor.html#Character-Highlighting CHARACTER HIGHLIGHTING]). Most terminals support the following colors by name:
+
Most terminals support the following colors by name:
  
 
{| class="wikitable"
 
{| class="wikitable"
 
|-
 
|-
! colspan="2" | Possible color values
+
! Name !! Number
 
|-
 
|-
| {{ic|black}} or {{ic|0}} || {{ic|red}} or {{ic|1}}
+
| {{ic|black}} || {{ic|0}}
 
|-
 
|-
| {{ic|green}} or {{ic|2}} || {{ic|yellow}} or {{ic|3}}
+
| {{ic|red}} || {{ic|1}}
 
|-
 
|-
| {{ic|blue}} or {{ic|4}} || {{ic|magenta}} or {{ic|5}}
+
| {{ic|green}} || {{ic|2}}
 
|-
 
|-
| {{ic|cyan}} or {{ic|6}} || {{ic|white}} or {{ic|7}}
+
| {{ic|yellow}} || {{ic|3}}
 +
|-
 +
| {{ic|blue}} || {{ic|4}}
 +
|-
 +
| {{ic|magenta}} || {{ic|5}}
 +
|-
 +
| {{ic|cyan}} || {{ic|6}}
 +
|-
 +
| {{ic|white}} || {{ic|7}}
 
|}
 
|}
  
{{Note| Bold text does not necessarily use the same colors as normal text. For example, {{ic|%F{yellow}''text''%f}} looks brown or a very dark yellow, while {{ic|%F{yellow}%B''text''%b%f}} looks like bright or regular yellow.}}
+
Color numbers 0–255 for terminal emulators compatible with xterm 256 colors can be found in the [https://upload.wikimedia.org/wikipedia/commons/1/15/Xterm_256color_chart.svg xterm-256color chart].
  
{{Tip|Prompt escapes can be tested with command {{ic|print -P ''"prompt escapes"''}}, for example:
+
With a correctly set TERM environment variable, the terminal's supported maximum number of colors can be found from the {{man|5|terminfo}} database using {{ic|echoti colors}}. In the case of [https://gist.github.com/XVilka/8346728 24-bit colors], also check the COLORTERM environment variable with {{ic|echo $COLORTERM}}. If it returns {{ic|24bit}} or {{ic|truecolor}} then your terminal supports 16777216 (2<sup>24</sup>) colors even if terminfo shows a smaller number.
  
$ print -P '%B%F{red}co%F{green}lo%F{blue}rs%f%b'
+
{{Note|
 +
* The colors 0–15 may differ between terminal emulators and their used color schemes.
 +
* Many terminal emulators display bold with a brighter color.
 +
}}
  
 +
{{Tip|
 +
* Prompt escapes can be tested with command {{ic|print -P ''"prompt escapes"''}}, for example: {{bc|$ print -P '%B%F{red}co%F{green}lo%F{blue}rs%f%b'}}
 +
* If you use 24-bit colors, you might want to load the {{ic|zsh/nearcolor}} module in terminals that do not support them. E.g.: {{bc|<nowiki>[[ "$COLORTERM" == (24bit|truecolor) || "${terminfo[colors]}" -eq '16777216' ]] || zmodload zsh/nearcolor</nowiki>}} See {{man|1|zshmodules|THE ZSH/NEARCOLOR MODULE}} for details about the {{ic|zsh/nearcolor}} module.
 
}}
 
}}
  
 
===== Example =====
 
===== Example =====
 +
 +
{{Expansion|Add an example using a color from the 16–255 range and one with 24-bit color.}}
  
 
This is an example of a two-sided prompt:
 
This is an example of a two-sided prompt:
  
  PROMPT='%F{red}%n%f@%F{blue}%m%f %F{yellow}%1~%f %# '
+
  PROMPT='%F{green}%n%f@%F{magenta}%m%f %F{blue}%B%~%b%f %# '
 
  RPROMPT='[%F{yellow}%?%f]'
 
  RPROMPT='[%F{yellow}%?%f]'
  
And here's how it will be displayed:
+
And here is how it will be displayed:
  
username@host ~ %                                                         [0]
+
<div style="font-family: monospace; white-space: pre; padding: 1em; background-color: #000; border: 1px solid #bcd; color: #c0c0c0; overflow: hidden;"><span style="float:left;"><span style="color: #008000;">username</span>@<span style="color: #800080;">host</span> <span style="color: #0000ff;">~</span> % </span><span style="float:right;">[<span style="color: #808000;">0</span>]</span></div>
  
 
=== Sample .zshrc files ===
 
=== Sample .zshrc files ===
  
* A package in offical repository named {{Pkg|grml-zsh-config}} comes from https://grml.org/zsh and provides a zshrc file that includes many tweaks for Zshell. This is the default configuration for the [https://www.archlinux.org/download/ monthly ISO releases].
+
* To get the same setup as the [https://www.archlinux.org/download/ monthly ISO releases] (which use Zsh by default), install {{Pkg|grml-zsh-config}}. It includes the many tweaks and advanced optimizations from [https://grml.org/zsh/ grml].
 
* https://github.com/MrElendig/dotfiles-alice/blob/master/.zshrc - basic setup, with dynamic prompt and window title/hardinfo.
 
* https://github.com/MrElendig/dotfiles-alice/blob/master/.zshrc - basic setup, with dynamic prompt and window title/hardinfo.
* https://github.com/slashbeast/things/blob/master/configs/DOTzshrc - zshrc with multiple features, be sure to check out comments into it. Notable features: confirm function to ensure that user want to run poweroff, reboot or hibernate, support for GIT in prompt (done without vcsinfo), tab completion with menu, printing current executed command into window's title bar and more.
+
* https://github.com/slashbeast/conf-mgmt/blob/master/roles/home_files/files/DOTzshrc - zshrc with multiple features, be sure to check out comments into it. Notable features: confirm function to ensure that user want to run poweroff, reboot or hibernate, support for GIT in prompt (done without vcsinfo), tab completion with menu, printing current executed command into window's title bar and more.
 
 
See [[dotfiles#Repositories]] for more.
 
 
 
=== Configuration Frameworks ===
 
 
 
* {{App|Antigen|A plugin manager for zsh, inspired by oh-my-zsh and vundle.|https://github.com/zsh-users/antigen|{{AUR|antigen-git}}}}
 
* {{App|oh-my-zsh|A popular, community-driven framework for managing your Zsh configuration. It comes bundled with a ton of helpful functions, helpers, plugins, themes.|https://github.com/robbyrussell/oh-my-zsh|{{AUR|oh-my-zsh-git}}}}
 
 
 
:{{Note|For themes to work you may need to set {{ic|setopt NO_GLOBAL_RCS}} in the {{ic|~/.zshenv}} file, otherwise changes to some variables (such as {{ic|$PROMPT}}) may be overwritten.}}
 
  
* {{App|Prezto|A configuration framework for Zsh. It comes with modules, enriching the command line interface environment with sane defaults, aliases, functions, auto completion, and prompt themes.|https://github.com/sorin-ionescu/prezto|{{AUR|prezto-git}}}}
+
See [[dotfiles#User repositories]] for more.
  
 
== Tips and tricks ==
 
== Tips and tricks ==
Line 249: Line 353:
 
=== Autostart X at login ===
 
=== Autostart X at login ===
  
See [[Xinitrc#Autostart X at login]].
+
See [[xinit#Autostart X at login]].
  
=== The "command not found" hook ===
+
=== The ttyctl command ===
  
[[pkgfile]] includes a "command not found" hook that will automatically search the official repositories, when entering an unrecognized command.
+
{{Expansion|{{ic|ttyctl -f}} does not protect against {{ic|echo -e '\e(0\e)B'}}. Provide an alternative using escape sequences in PROMPT.[https://www.in-ulm.de/~mascheck/various/alternate_charset/]}}
  
You need to [[source]] the hook to enable it, for example:
+
The [http://zsh.sourceforge.net/Doc/Release/Shell-Builtin-Commands.html#index-tty_002c-freezing ttyctl] command can be used to "freeze/unfreeze" the terminal. Many programs change the terminal state, and often do not restore terminal settings on exiting abnormally. To avoid the need to manually reset the terminal, use the following:
 
 
{{hc|~/.zshrc|
 
source /usr/share/doc/pkgfile/command-not-found.zsh
 
}}
 
 
 
=== The ttyctl command ===
 
 
 
[http://zsh.sourceforge.net/Doc/Release/Shell-Builtin-Commands.html#index-tty_002c-freezing] describes the {{ic|ttyctl}} command in Zsh.
 
This may be used to "freeze/unfreeze" the terminal.
 
Many programs change the terminal state, and often do not restore terminal settings on exiting abnormally.
 
To avoid the need to manually reset the terminal, use the following:
 
  
 
{{hc|~/.zshrc|
 
{{hc|~/.zshrc|
Line 278: Line 371:
 
Zsh can be configured to remember the DIRSTACKSIZE last visited folders. This can then be used to ''cd'' them very quickly. You need to add some lines to your configuration file:
 
Zsh can be configured to remember the DIRSTACKSIZE last visited folders. This can then be used to ''cd'' them very quickly. You need to add some lines to your configuration file:
  
{{hc|.zshrc|<nowiki>
+
{{hc|~/.zshrc|<nowiki>
DIRSTACKFILE="$HOME/.cache/zsh/dirs"
+
autoload -Uz add-zsh-hook
if [[ -f $DIRSTACKFILE ]] && [[ $#dirstack -eq 0 ]]; then
+
 
  dirstack=( ${(f)"$(< $DIRSTACKFILE)"} )
+
DIRSTACKFILE="${XDG_CACHE_HOME:-$HOME/.cache}/zsh/dirs"
  [[ -d $dirstack[1] ]] && cd $dirstack[1]
+
if [[ -f "$DIRSTACKFILE" ]] && (( ${#dirstack} == 0 )); then
 +
dirstack=("${(@f)"$(< "$DIRSTACKFILE")"}")
 +
[[ -d "${dirstack[1]}" ]] && cd -- "${dirstack[1]}"
 
fi
 
fi
chpwd() {
+
chpwd_dirstack() {
  print -l $PWD ${(u)dirstack} >$DIRSTACKFILE
+
print -l -- "$PWD" "${(u)dirstack[@]}" > "$DIRSTACKFILE"
 
}
 
}
 +
add-zsh-hook -Uz chpwd chpwd_dirstack
  
DIRSTACKSIZE=20
+
DIRSTACKSIZE='20'
  
 
setopt AUTO_PUSHD PUSHD_SILENT PUSHD_TO_HOME
 
setopt AUTO_PUSHD PUSHD_SILENT PUSHD_TO_HOME
Line 311: Line 407:
 
cdr allows you to change the working directory to a previous working directory from a list maintained automatically. It stores all entries in files that are maintained across sessions and (by default) between terminal emulators in the current session.
 
cdr allows you to change the working directory to a previous working directory from a list maintained automatically. It stores all entries in files that are maintained across sessions and (by default) between terminal emulators in the current session.
  
See [http://zsh.sourceforge.net/Doc/Release/User-Contributions.html#Recent-Directories Remembering Recent Directories] in {{man|1|zshcontrib}}.
+
See {{man|1|zshcontrib|REMEMBERING RECENT DIRECTORIES}} for setup instructions.
  
 
=== Help command ===
 
=== Help command ===
  
Zsh {{ic|help}} command is called {{ic|run-help}}. Unlike [[bash]], ''zsh'' does not enable it by default. To use {{ic|help}} in zsh, add following to your {{ic|zshrc}}:
+
Unlike [[Bash]], Zsh does not enable a built in {{ic|help}} command, instead it provides {{ic|run-help}}. By default {{ic|run-help}} is an alias to {{ic|man}}, it can be either executed manually by prepending it to a command or it can be invoked for the currently typed command with the keyboard shortcuts {{ic|Alt+h}} or {{ic|Esc}} {{ic|h}}.
 +
 
 +
Since by default it is just an alias to [[man]], it will only work on external commands. To improve its functionality, so that it works on shell builtins and other shell features, you need to use the {{ic|run-help}} function. See {{man|1|zshcontrib}} for more information on the {{ic|run-help}} and its assistant functions.
 +
 
 +
First load the {{ic|run-help}} function and then remove the existing {{ic|run-help}} alias. For convenience {{ic|help}} can be aliased to {{ic|run-help}}. For example, add following to your {{ic|zshrc}}:
  
 
{{bc|1=
 
{{bc|1=
Line 323: Line 423:
 
}}
 
}}
  
{{ic|run-help}} will invoke ''man'' for external commands. Default keyboard shortcut is {{ic|Alt+h}} or {{ic|Esc+h}}.
+
Assistant functions have to be enabled separately:
 
 
{{ic|run-help}} has helper functions, they need to be enabled separately:
 
  
 
{{bc|1=
 
{{bc|1=
Line 337: Line 435:
 
}}
 
}}
  
For example {{ic|run-help git commit}} command will now open the man page {{man|1|git-commit}} instead of {{man|1|git}}.
+
For example, {{ic|run-help git commit}} command will now open the [[man page]] {{man|1|git-commit}} instead of {{man|1|git}}.
 
 
=== Fish-like syntax highlighting ===
 
 
 
[[Fish]] provides a very powerful shell syntax highlighting. To use this in zsh, you can install {{pkg|zsh-syntax-highlighting}} from offical repository and add following to your zshrc:
 
 
 
source /usr/share/zsh/plugins/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh
 
  
 
=== Persistent rehash ===
 
=== Persistent rehash ===
  
Typically, compinit will not automatically find new executables in the {{ic|$PATH}}. For example, after you install a new package, the files in /usr/bin would not be immediately or automatically included in the completion. Thus, to have these new exectuables included, one would run:
+
Typically, compinit will not automatically find new executables in the {{ic|$PATH}}. For example, after you install a new package, the files in {{ic|/usr/bin/}} would not be immediately or automatically included in the completion. Thus, to have these new executables included, one would run:
  
 
  $ rehash
 
  $ rehash
  
This 'rehash' can be set to happen automatically. Simply include the following in your {{ic|zshrc}}:
+
This 'rehash' can be set to happen automatically.[https://github.com/robbyrussell/oh-my-zsh/issues/3440] Simply include the following in your {{ic|zshrc}}:
  
 
{{hc|~/.zshrc|
 
{{hc|~/.zshrc|
Line 357: Line 449:
 
}}
 
}}
  
{{Note|This hack has been found in a [https://github.com/robbyrussell/oh-my-zsh/issues/3440 PR for Oh My Zsh].}}
+
==== On-demand rehash ====
 +
 
 +
As above, however [[pacman]] can be configured with [[Pacman#Hooks|hooks]] to automatically request a {{ic|rehash}}, which does not incur the performance penalty of constant rehashing as above. To enable this, create the {{ic|/etc/pacman.d/hooks}} directory, and a {{ic|/var/cache/zsh}} directory, then create a hook file:
 +
 
 +
{{hc|head=/etc/pacman.d/hooks/zsh.hook|output=
 +
[Trigger]
 +
Operation = Install
 +
Operation = Upgrade
 +
Operation = Remove
 +
Type = Path
 +
Target = usr/bin/*
 +
[Action]
 +
Depends = zsh
 +
When = PostTransaction
 +
Exec = /usr/bin/install -Dm644 /dev/null /var/cache/zsh/pacman
 +
}}
 +
 
 +
This keeps the modification date of the file {{ic|/var/cache/zsh/pacman}} consistent with the last time a package was installed, upgraded or removed. Then, {{ic|zsh}} must be coaxed into rehashing its own command cache when it goes out of date, by adding to your {{ic|~/.zshrc}}:
 +
 
 +
{{hc|~/.zshrc|<nowiki>
 +
zshcache_time="$(date +%s%N)"
 +
 
 +
autoload -Uz add-zsh-hook
 +
 
 +
rehash_precmd() {
 +
  if [[ -a /var/cache/zsh/pacman ]]; then
 +
    local paccache_time="$(date -r /var/cache/zsh/pacman +%s%N)"
 +
    if (( zshcache_time < paccache_time )); then
 +
      rehash
 +
      zshcache_time="$paccache_time"
 +
    fi
 +
  fi
 +
}
 +
 
 +
add-zsh-hook -Uz precmd rehash_precmd
 +
</nowiki>}}
 +
 
 +
If the {{ic|precmd}} hook is triggered before {{ic|/var/cache/zsh/pacman}} is updated, completion may not work until a new prompt is initiated. Running an empty command, e.g. pressing {{ic|enter}}, should be sufficient.
 +
 
 +
==== Alternative on-demand rehash using SIGUSR1 ====
 +
 
 +
As above, however the hook file looks like this:
 +
 
 +
{{hc|/etc/pacman.d/hooks/zsh-rehash.hook|output=
 +
[Trigger]
 +
Operation = Install
 +
Operation = Upgrade
 +
Operation = Remove
 +
Type = Path
 +
Target = usr/bin/*
 +
 
 +
[Action]
 +
Depends = zsh
 +
Depends = procps-ng
 +
When = PostTransaction
 +
Exec = /usr/bin/pkill zsh --signal=USR1
 +
}}
 +
 
 +
{{Warning|This sends SIGUSR1 to all running {{ic|zsh}} instances. Note that the default behavior for SIGUSR1 is terminate so when you first configure this all running {{ic|zsh}} instances of all users (including login shells) will terminate if they have not sourced the trap below.}}
 +
 
 +
{{hc|~/.zshrc|<nowiki>
 +
catch_signal_usr1() {
 +
  trap catch_signal_usr1 USR1
 +
  rehash
 +
}
 +
trap catch_signal_usr1 USR1
 +
</nowiki>}}
 +
 
 +
This method will instantly {{ic|rehash}} all {{ic|zsh}} instances, removing the need to press enter to trigger {{ic|precmd}}.
  
 
=== Bind key to ncurses application ===
 
=== Bind key to ncurses application ===
  
Bind a ncurses application to a keystoke, but it will not accept interaction. Use {{ic|BUFFER}} variable to make it work. The following example lets users open ncmpcpp using {{ic|Alt+\}}:
+
Bind a ncurses application to a keystroke, but it will not accept interaction. Use {{ic|BUFFER}} variable to make it work. The following example lets users open ncmpcpp using {{ic|Alt+\}}:
  
 
{{hc|~/.zshrc|2=
 
{{hc|~/.zshrc|2=
ncmpcppShow() { BUFFER="ncmpcpp"; zle accept-line; }
+
ncmpcppShow() {
 +
  BUFFER="ncmpcpp"
 +
  zle accept-line
 +
}
 
zle -N ncmpcppShow
 
zle -N ncmpcppShow
 
bindkey '^[\' ncmpcppShow
 
bindkey '^[\' ncmpcppShow
Line 372: Line 535:
  
 
{{hc|~/.zshrc|2=
 
{{hc|~/.zshrc|2=
ncmpcppShow() { ncmpcpp <$TTY; zle redisplay; }
+
ncmpcppShow() {
 +
  ncmpcpp <$TTY
 +
  zle redisplay
 +
}
 
zle -N ncmpcppShow
 
zle -N ncmpcppShow
 
bindkey '^[\' ncmpcppShow
 
bindkey '^[\' ncmpcppShow
Line 406: Line 572:
 
=== xterm title ===
 
=== xterm title ===
  
xterm title is set with [http://tldp.org/HOWTO/Xterm-Title-3.html#ss3.1 xterm escape sequences]. For example:
+
If your terminal emulator supports it, you can set its title from Zsh. This allows dynamically changing the title to display relevant information about the shell state, for example showing the user name and current directory or the currently executing command.
 +
 
 +
The xterm title is set with the [https://www.tldp.org/HOWTO/Xterm-Title-3.html#ss3.1 xterm escape sequence] {{ic|\e]2;}}{{ic|\a}}. For example:
  
 
  $ print -n '\e]2;My xterm title\a'
 
  $ print -n '\e]2;My xterm title\a'
Line 414: Line 582:
 
  My xterm title
 
  My xterm title
  
An simple way to have a dynamic title is to set the title in a [http://zsh.sourceforge.net/Doc/Release/Functions.html#Hook-Functions hook function], particularly {{ic|precmd}} and {{ic|preexec}}.
+
A simple way to have a dynamic title is to set the title in the {{ic|precmd}} and {{ic|preexec}} hook functions. See {{man|1|zshmisc|Hook Functions}} for a list of available hook functions and their descriptions.
  
By using {{ic|print -P}} you can take advantage of prompt escapes. Title printing can be split up in multiple commands as long as they are sequential.
+
By using {{ic|print -P}} you can additionally take advantage of Zsh's prompt escapes.
 +
 
 +
{{Tip|
 +
* Title printing can be split up in multiple commands as long as they are sequential.
 +
* [[GNU Screen]] sends the xterm title to the hardstatus ({{ic|%h}}). If you want to use Screen's [https://www.gnu.org/software/screen/manual/html_node/String-Escapes.html string escapes] (e.g. for colors) you should set the hardstatus with the {{ic|\e_}}{{ic|\e\\}} escape sequence. Otherwise, if string escapes are used in {{ic|\e]2;}}{{ic|\a}}, the terminal emulator will get a garbled title due to it being incapable of interpreting Screen's string escapes.
 +
}}
 +
 
 +
{{Note|
 +
* Do not use the {{ic|-P}} option of {{ic|print}} when printing variables to prevent them from being parsed as prompt escapes.
 +
* Use the {{ic|q}} [http://zsh.sourceforge.net/Doc/Release/Expansion.html#Parameter-Expansion-Flags parameter expansion flag] when printing variables to prevent them from being parsed as escape sequences.
 +
}}
  
 
{{hc|~/.zshrc|<nowiki>
 
{{hc|~/.zshrc|<nowiki>
Line 422: Line 600:
  
 
function xterm_title_precmd () {
 
function xterm_title_precmd () {
print -Pn '\e]2;%n@%m %1~\a'
+
print -Pn -- '\e]2;%n@%m %~\a'
 +
[[ "$TERM" == 'screen'* ]] && print -Pn -- '\e_\005{g}%n\005{-}@\005{m}%m\005{-} \005{B}%~\005{-}\e\\'
 
}
 
}
  
 
function xterm_title_preexec () {
 
function xterm_title_preexec () {
print -Pn '\e]2;%n@%m %1~ %# '
+
print -Pn -- '\e]2;%n@%m %~ %# ' && print -n -- "${(q)1}\a"
print -n "${(q)1}\a"
+
[[ "$TERM" == 'screen'* ]] && { print -Pn -- '\e_\005{g}%n\005{-}@\005{m}%m\005{-} \005{B}%~\005{-} %# ' && print -n -- "${(q)1}\e\\"; }
 
}
 
}
  
if [[ "$TERM" == (screen*|xterm*|rxvt*) ]]; then
+
if [[ "$TERM" == (alacritty*|gnome*|konsole*|putty*|rxvt*|screen*|tmux*|xterm*) ]]; then
 
add-zsh-hook -Uz precmd xterm_title_precmd
 
add-zsh-hook -Uz precmd xterm_title_precmd
 
add-zsh-hook -Uz preexec xterm_title_preexec
 
add-zsh-hook -Uz preexec xterm_title_preexec
Line 436: Line 615:
 
</nowiki>}}
 
</nowiki>}}
  
{{Warning|
+
==== Terminal emulator tab title ====
* Do not use {{ic|-P}} option of {{ic|print}} when printing variables to prevent them from being parsed as prompt escapes.
+
 
* Use {{ic|q}} [http://zsh.sourceforge.net/Doc/Release/Expansion.html#Parameter-Expansion-Flags parameter expansion flag] when printing variables to prevent them from being parsed as escape sequences.
+
Some terminal emulators and multiplexers support setting the title of the tab. The escape sequences depend on the terminal:
 +
 
 +
{| class="wikitable sortable"
 +
! Terminal
 +
! Escape sequences
 +
! Description
 +
|-
 +
! [[GNU Screen]]
 +
| {{ic|\ek}}{{ic|\e\\}}
 +
| Screen's window title ({{ic|%t}}).
 +
|-
 +
! Konsole
 +
| {{ic|\e]30;}}{{ic|\a}}
 +
| Konsole's tab title.
 +
|}
 +
 
 +
=== Shell environment detection ===
 +
 
 +
See [https://gitlab.com/jdorel-documentation/shell-environment-detection a repository about shell environment detection] for tests to detect the shell environment. This includes login/interactive shell, Xorg session, TTY and SSH session.
 +
 
 +
=== /dev/tcp equivalent: ztcp ===
 +
 
 +
Use the {{ic|zsh/net/tcp}} module:
 +
 
 +
$ zmodload zsh/net/tcp
 +
 
 +
You can now establish TCP connections:
 +
 
 +
$ ztcp example.com 80
 +
 
 +
=== Shortcut to exit shell on partial command line ===
 +
 
 +
By default, {{ic|Ctrl+d}} will not close your shell if the command line is filled, this fixes it:
 +
 
 +
{{hc|.zshrc|
 +
exit_zsh() { exit }
 +
zle -N exit_zsh
 +
bindkey '^D' exit_zsh
 
}}
 
}}
 +
 +
== Third-party extensions ==
 +
 +
=== Configuration frameworks ===
 +
 +
* {{App|oh-my-zsh|A popular, community-driven framework for managing your Zsh configuration. It comes bundled with a ton of helpful functions, helpers, plugins, themes.|https://github.com/robbyrussell/oh-my-zsh|{{AUR|oh-my-zsh-git}}}}
 +
* {{App|Prezto|A configuration framework for Zsh. It comes with modules, enriching the command line interface environment with sane defaults, aliases, functions, auto completion, and prompt themes.|https://github.com/sorin-ionescu/prezto|{{AUR|prezto-git}}}}
 +
* {{App|ZIM|A configuration framework with blazing speed and modular extensions. Zim is very easy to customize, and comes with a rich set of modules and features without compromising on speed or functionality.|https://github.com/zimfw/zimfw|{{AUR|zsh-zim-git}}}}
 +
 +
=== Plugin managers ===
 +
 +
* {{App|Antibody|A performance-focused plugin manager similar to Antigen.|https://github.com/getantibody/antibody|{{AUR|antibody}}}}
 +
* {{App|zinit (previously "zplugin")|Flexible Zsh plugin manager with clean fpath, reports, completion management, turbo mode|http://github.com/zdharma/zinit|{{AUR|zsh-zplugin-git}}}}
 +
* {{App|Antigen|A plugin manager for Zsh, inspired by oh-my-zsh and vundle. [https://github.com/zsh-users/antigen/issues/673 ABANDONED]|https://github.com/zsh-users/antigen|{{AUR|antigen-git}}}}
 +
* {{App|zgen|A lightweight and simple plugin manager for Zsh. [https://github.com/tarjoilija/zgen/issues/123 ABANDONED]|https://github.com/tarjoilija/zgen|{{AUR|zgen-git}}}}
 +
* {{App|zplug|A next-generation plugin manager for Zsh. [https://github.com/zplug/zplug/issues/403#issuecomment-477520784 ABANDONED]|https://github.com/zplug/zplug|{{AUR|zplug}}}}
 +
 +
=== Fish-like syntax highlighting ===
 +
 +
[[Fish]] provides a very powerful shell syntax highlighting. To use this in Zsh, you can install {{pkg|zsh-syntax-highlighting}} and [[source]] the provided script from your zshrc:
 +
 +
source /usr/share/zsh/plugins/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh
 +
 +
=== The "command not found" handler ===
 +
 +
[[pkgfile]] includes a Zsh script file that provides a {{ic|command_not_found_handler}} function that will automatically search the official repositories, when entering an unrecognized command.
 +
 +
You need to [[source]] the script to enable it. For example:
 +
 +
{{hc|~/.zshrc|
 +
source /usr/share/doc/pkgfile/command-not-found.zsh
 +
}}
 +
 +
{{Note|The pkgfile database may need to be updated before this will work. See [[pkgfile#Installation]] for details.}}
  
 
== Uninstallation ==
 
== Uninstallation ==
Line 455: Line 705:
 
Alternatively, change the default shell back to Bash by editing {{ic|/etc/passwd}} as root.
 
Alternatively, change the default shell back to Bash by editing {{ic|/etc/passwd}} as root.
  
{{Warning|It is strongly recommended to use {{ic|vipw}} when editing {{ic|/etc/passwd}} as it helps prevent invalid entries and/or syntax errors.}}
+
{{Warning|It is strongly recommended to use {{man|8|vipw}} when editing {{ic|/etc/passwd}} as it helps prevent invalid entries and/or syntax errors.}}
  
 
For example, change the following:
 
For example, change the following:
Line 467: Line 717:
 
== See also ==
 
== See also ==
  
 +
* [[Wikipedia:Zsh]]
 +
* [http://zsh.sourceforge.net/Intro/intro_toc.html An Introduction to the Z Shell]
 
* [http://zsh.sourceforge.net/Guide/zshguide.html A User's Guide to ZSH]
 
* [http://zsh.sourceforge.net/Guide/zshguide.html A User's Guide to ZSH]
 
* [http://zsh.sourceforge.net/Doc/Release/index-frame.html The Z Shell Manual] (different format available [http://zsh.sourceforge.net/Doc/ here])
 
* [http://zsh.sourceforge.net/Doc/Release/index-frame.html The Z Shell Manual] (different format available [http://zsh.sourceforge.net/Doc/ here])
 
* [http://zsh.sourceforge.net/FAQ/zshfaq01.html Zsh FAQ]
 
* [http://zsh.sourceforge.net/FAQ/zshfaq01.html Zsh FAQ]
 +
* [http://zshwiki.org/home/ Zsh Wiki]
 
* {{man|1|zsh-lovers}} (available as {{pkg|zsh-lovers}} package)
 
* {{man|1|zsh-lovers}} (available as {{pkg|zsh-lovers}} package)
* [http://zshwiki.org/home/ Zsh Wiki]
 
 
* [[Gentoo: Zsh/Guide]]
 
* [[Gentoo: Zsh/Guide]]
 
* [http://www.bash2zsh.com/zsh_refcard/refcard.pdf Bash2Zsh Reference Card]
 
* [http://www.bash2zsh.com/zsh_refcard/refcard.pdf Bash2Zsh Reference Card]

Latest revision as of 14:51, 27 March 2020

Zsh is a powerful shell that operates as both an interactive shell and as a scripting language interpreter. While being compatible with the POSIX sh (not by default, only if issuing emulate sh), it offers advantages such as improved tab completion and globbing.

The Zsh FAQ offers more reasons to use Zsh.

Installation

Before starting, users may want to see what shell is currently being used:

$ echo $SHELL

Install the zsh package. For additional completion definitions, install the zsh-completions package as well.

Initial configuration

Make sure that Zsh has been installed correctly by running the following in a terminal:

$ zsh

You should now see zsh-newuser-install, which will walk you through some basic configuration. If you want to skip this, press q. If you did not see it, you can invoke it manually with:

$ autoload -Uz zsh-newuser-install
$ zsh-newuser-install -f
Note: Make sure your terminal's size is at least 72×15 otherwise zsh-newuser-install will not run.

Making Zsh your default shell

Change your shell to /usr/bin/zsh. See Command-line shell#Changing your default shell.

Tip: If replacing bash, users may want to move some code from ~/.bashrc to ~/.zshrc (e.g. the prompt and the aliases) and from ~/.bash_profile to ~/.zprofile (e.g. the code that starts the X Window System).

Startup/Shutdown files

Tip:
Note:
  • If $ZDOTDIR is not set, $HOME is used instead.
  • If option RCS is unset in any of the files, no configuration files will be read after that file.
  • If option GLOBAL_RCS is unset in any of the files, no global configuration files (/etc/zsh/*) will be read after that file.

When starting, Zsh will read commands from the following files in this order by default:

  • /etc/zsh/zshenv Used for setting environment variables for all users; it should not contain commands that produce output or assume the shell is attached to a TTY. This file will always be read, this cannot be overridden.
  • $ZDOTDIR/.zshenv Used for setting user's environment variables; it should not contain commands that produce output or assume the shell is attached to a TTY. This file will always be read.
  • /etc/zsh/zprofile Used for executing commands at start for all users, will be read when starting as a login shell. Please note that on Arch Linux, by default it contains one line which source the /etc/profile. See warning below before wanting to remove that!
    • /etc/profile This file should be sourced by all POSIX sh-compatible shells upon login: it sets up $PATH and other environment variables and application-specific (/etc/profile.d/*.sh) settings upon login.
  • $ZDOTDIR/.zprofile Used for executing user's commands at start, will be read when starting as a login shell. Typically used to autostart graphical sessions and to set session-wide environment variables.
  • /etc/zsh/zshrc Used for setting interactive shell configuration and executing commands for all users, will be read when starting as an interactive shell.
  • $ZDOTDIR/.zshrc Used for setting user's interactive shell configuration and executing commands, will be read when starting as an interactive shell.
  • /etc/zsh/zlogin Used for executing commands for all users at ending of initial progress, will be read when starting as a login shell.
  • $ZDOTDIR/.zlogin Used for executing user's commands at ending of initial progress, will be read when starting as a login shell. Typically used to autostart command line utilities. Should not be used to autostart graphical sessions, as at this point the session might contain configuration meant only for an interactive shell.
  • $ZDOTDIR/.zlogout Used for executing commands when a login shell exits.
  • /etc/zsh/zlogout Used for executing commands for all users when a login shell exits.

See the graphic representation.

Note:
  • $HOME/.profile is not a part of the Zsh startup files and is not sourced by Zsh unless Zsh is invoked as sh or ksh and started as a login shell. For more details about the sh and ksh compatibility modes refer to zsh(1).
  • The paths used in Arch's zsh package are different from the default ones used in the man pages (FS#48992).
Warning: Do not remove the default one line in /etc/zsh/zprofile, otherwise it will break the integrity of other packages which provide some scripts in /etc/profile.d/.

Configure Zsh

Although Zsh is usable out of the box, it is almost certainly not set up the way most users would like to use it, but due to the sheer amount of customization available in Zsh, configuring Zsh can be a daunting and time-consuming experience.

Simple .zshrc

Included below is a sample configuration file, it provides a decent set of default options as well as giving examples of many ways that Zsh can be customized. In order to use this configuration save it as a file named .zshrc.

Tip: Apply the changes without needing to logout and then back in by running source ~/.zshrc.

Here is a simple .zshrc:

~/.zshrc
autoload -Uz compinit promptinit
compinit
promptinit

# This will set the default prompt to the walters theme
prompt walters

Configuring $PATH

Zsh ties the PATH variable to an path array. They are automatically synchronized. This allows us to easily manipulate PATH by simply modifying the array. See A User's Guide to the Z-Shell for details.

The line typeset -U PATH path, where the -U stands for unique, instructs the shell to discard duplicates from both $PATH and $path:

~/.zshenv
typeset -U PATH path
path=("$HOME/.local/bin" /other/things/in/path "$path[@]")
export PATH

Command completion

Perhaps the most compelling feature of Zsh is its advanced autocompletion abilities. At the very least, enable autocompletion in .zshrc. To enable autocompletion, add the following to your ~/.zshrc:

~/.zshrc
autoload -Uz compinit
compinit

The above configuration includes ssh/scp/sftp hostnames completion but in order for this feature to work, users must not enable ssh's hostname hashing (i.e. option HashKnownHosts in ssh client configuration).

For autocompletion with an arrow-key driven interface, add the following to:

~/.zshrc
zstyle ':completion:*' menu select

To activate the menu, press Tab twice.

For autocompletion of command line switches for aliases, add the following to:

~/.zshrc
setopt COMPLETE_ALIASES

For enabling autocompletion of privileged environments in privileged commands (e.g. if you complete a command starting with sudo, completion scripts will also try to determine your completions with sudo), include:

~/.zshrc
zstyle ':completion::complete:*' gain-privileges 1
Warning: This will let Zsh completion scripts run commands with sudo privileges. You should not enable this if you use untrusted autocompletion scripts.
Note: This special kind of context-aware completion is only available for a small number of commands.

Key bindings

Zsh does not use readline, instead it uses its own and more powerful Zsh Line Editor (ZLE). It does not read /etc/inputrc or ~/.inputrc. Read A closer look at the zsh line editor and creating custom widgets for an introduction to ZLE configuration.

ZLE has an Emacs mode and a vi mode. If one of the VISUAL or EDITOR environment variables contain the string vi then vi mode will be used; otherwise, it will default to Emacs mode. Set the mode explicitly with bindkey -e or bindkey -v respectively for Emacs mode or vi mode.

Key bindings are assigned by mapping an escape sequence matching a keypress to a ZLE widget. The available widgets, with descriptions of their actions and their default keybindings, are listed in zshzle(1) and zshcontrib(1).

The recommended way to set key bindings in Zsh is by using string capabilities from terminfo(5). For example[1][2]:

~/.zshrc
# create a zkbd compatible hash;
# to add other keys to this hash, see: man 5 terminfo
typeset -g -A key

key[Home]="${terminfo[khome]}"
key[End]="${terminfo[kend]}"
key[Insert]="${terminfo[kich1]}"
key[Backspace]="${terminfo[kbs]}"
key[Delete]="${terminfo[kdch1]}"
key[Up]="${terminfo[kcuu1]}"
key[Down]="${terminfo[kcud1]}"
key[Left]="${terminfo[kcub1]}"
key[Right]="${terminfo[kcuf1]}"
key[PageUp]="${terminfo[kpp]}"
key[PageDown]="${terminfo[knp]}"
key[Shift-Tab]="${terminfo[kcbt]}"

# setup key accordingly
[[ -n "${key[Home]}"      ]] && bindkey -- "${key[Home]}"      beginning-of-line
[[ -n "${key[End]}"       ]] && bindkey -- "${key[End]}"       end-of-line
[[ -n "${key[Insert]}"    ]] && bindkey -- "${key[Insert]}"    overwrite-mode
[[ -n "${key[Backspace]}" ]] && bindkey -- "${key[Backspace]}" backward-delete-char
[[ -n "${key[Delete]}"    ]] && bindkey -- "${key[Delete]}"    delete-char
[[ -n "${key[Up]}"        ]] && bindkey -- "${key[Up]}"        up-line-or-history
[[ -n "${key[Down]}"      ]] && bindkey -- "${key[Down]}"      down-line-or-history
[[ -n "${key[Left]}"      ]] && bindkey -- "${key[Left]}"      backward-char
[[ -n "${key[Right]}"     ]] && bindkey -- "${key[Right]}"     forward-char
[[ -n "${key[PageUp]}"    ]] && bindkey -- "${key[PageUp]}"    beginning-of-buffer-or-history
[[ -n "${key[PageDown]}"  ]] && bindkey -- "${key[PageDown]}"  end-of-buffer-or-history
[[ -n "${key[Shift-Tab]}" ]] && bindkey -- "${key[Shift-Tab]}" reverse-menu-complete

# Finally, make sure the terminal is in application mode, when zle is
# active. Only then are the values from $terminfo valid.
if (( ${+terminfo[smkx]} && ${+terminfo[rmkx]} )); then
	autoload -Uz add-zle-hook-widget
	function zle_application_mode_start { echoti smkx }
	function zle_application_mode_stop { echoti rmkx }
	add-zle-hook-widget -Uz zle-line-init zle_application_mode_start
	add-zle-hook-widget -Uz zle-line-finish zle_application_mode_stop
fi

History search

You need to set up the key array and make sure that ZLE enters application mode to use the following instructions; see #Key bindings.

To enable history search add these lines to .zshrc file:

~/.zshrc
autoload -Uz up-line-or-beginning-search down-line-or-beginning-search
zle -N up-line-or-beginning-search
zle -N down-line-or-beginning-search

[[ -n "${key[Up]}"   ]] && bindkey -- "${key[Up]}"   up-line-or-beginning-search
[[ -n "${key[Down]}" ]] && bindkey -- "${key[Down]}" down-line-or-beginning-search

By doing this, only the past commands matching the current line up to the current cursor position will be shown when Up or Down keys are pressed.

Shift, Alt, Ctrl and Meta modifiers

xterm-compatible terminals can use extended key-definitions from user_caps(5). Those are combinations of Shift, Alt, Ctrl and Meta together with Up, Down, Left, Right, PageUp, PageDown, Home, End or Del.

For example, for Ctrl+Left to move to the beginning of the previous word and Ctrl+Right to move to the beginning of the next word:

~/.zshrc
key[Control-Left]="${terminfo[kLFT5]}"
key[Control-Right]="${terminfo[kRIT5]}"

[[ -n "${key[Control-Left]}"  ]] && bindkey -- "${key[Control-Left]}"  backward-word
[[ -n "${key[Control-Right]}" ]] && bindkey -- "${key[Control-Right]}" forward-word

Prompts

Zsh offers the options of using a prompt theme or, for users who are dissatisfied with the themes (or want to expand their usefulness), the possibility to build a custom prompt.

Prompt themes

Prompt themes are a quick and easy way to set up a colored prompt in Zsh. See zshcontrib(1) for more information about them.

To use a theme, make sure that prompt theme system is set to autoload in .zshrc. This can be done by adding these lines to:

~/.zshrc
autoload -Uz promptinit
promptinit

Available prompt themes are listed by running the command:

$ prompt -l

For example, to use the walters theme, enter:

$ prompt walters

To preview all available themes, use this command:

$ prompt -p
Manually installing prompt themes

It is possible to install themes manually, without external configuration manager tools. For a local installation, first create a folder and add it to the fpath array, eg:

$ mkdir ~/.zprompts
$ fpath=("$HOME/.zprompts" "$fpath[@]")

Now create a symbolic link of your theme file in this folder:

$ ln -s mytheme.zsh ~/.zprompts/prompt_mytheme_setup

If instead you wish to install a theme globally, do:

# ln -s mytheme.zsh /usr/share/zsh/functions/Prompts/prompt_mytheme_setup

Now you should be able to activate it using:

$ prompt mytheme

If everything works, you can edit your .zshrc accordingly.

Customized prompt

Tango-view-fullscreen.pngThis article or section needs expansion.Tango-view-fullscreen.png

Reason: Add a simple colorless PROMPT example. (Discuss in Talk:Zsh#)

Additionally to a primary left-sided prompt PS1 (PROMPT, prompt) that is common to all shells, Zsh also supports a right-sided prompt RPS1 (RPROMPT). These two variables are the ones you will want to set to a custom value.

Other special purpose prompts, such as PS2 (PROMPT2), PS3 (PROMPT3), PS4 (PROMPT4), RPS1 (RPROMPT), RPS2 (RPROMPT2) and SPROMPT, are explained in zshparam(1).

All prompts can be customized with prompt escapes. The available prompt escapes are listed in zshmisc(1).

Colors

Zsh sets colors differently than Bash, you do not need to use convoluted ANSI escape sequences or terminal capabilities from terminfo(5). Zsh provides convenient prompt escapes to set the foreground color, background color and other visual effects; see zshmisc(1) for a list of them and their descriptions.

Colors can be specified using a decimal integer, the name of one of the eight most widely-supported colors or as a # followed by an RGB triplet in hexadecimal format. See the description of fg=colour in zshzle(1) for more details.

Most terminals support the following colors by name:

Name Number
black 0
red 1
green 2
yellow 3
blue 4
magenta 5
cyan 6
white 7

Color numbers 0–255 for terminal emulators compatible with xterm 256 colors can be found in the xterm-256color chart.

With a correctly set TERM environment variable, the terminal's supported maximum number of colors can be found from the terminfo(5) database using echoti colors. In the case of 24-bit colors, also check the COLORTERM environment variable with echo $COLORTERM. If it returns 24bit or truecolor then your terminal supports 16777216 (224) colors even if terminfo shows a smaller number.

Note:
  • The colors 0–15 may differ between terminal emulators and their used color schemes.
  • Many terminal emulators display bold with a brighter color.
Tip:
  • Prompt escapes can be tested with command print -P "prompt escapes", for example:
    $ print -P '%B%F{red}co%F{green}lo%F{blue}rs%f%b'
  • If you use 24-bit colors, you might want to load the zsh/nearcolor module in terminals that do not support them. E.g.:
    [[ "$COLORTERM" == (24bit|truecolor) || "${terminfo[colors]}" -eq '16777216' ]] || zmodload zsh/nearcolor
    See zshmodules(1) for details about the zsh/nearcolor module.
Example

Tango-view-fullscreen.pngThis article or section needs expansion.Tango-view-fullscreen.png

Reason: Add an example using a color from the 16–255 range and one with 24-bit color. (Discuss in Talk:Zsh#)

This is an example of a two-sided prompt:

PROMPT='%F{green}%n%f@%F{magenta}%m%f %F{blue}%B%~%b%f %# '
RPROMPT='[%F{yellow}%?%f]'

And here is how it will be displayed:

username@host ~ % [0]

Sample .zshrc files

See dotfiles#User repositories for more.

Tips and tricks

Autostart X at login

See xinit#Autostart X at login.

The ttyctl command

Tango-view-fullscreen.pngThis article or section needs expansion.Tango-view-fullscreen.png

Reason: ttyctl -f does not protect against echo -e '\e(0\e)B'. Provide an alternative using escape sequences in PROMPT.[3] (Discuss in Talk:Zsh#)

The ttyctl command can be used to "freeze/unfreeze" the terminal. Many programs change the terminal state, and often do not restore terminal settings on exiting abnormally. To avoid the need to manually reset the terminal, use the following:

~/.zshrc
ttyctl -f

Remembering recent directories

Dirstack

Zsh can be configured to remember the DIRSTACKSIZE last visited folders. This can then be used to cd them very quickly. You need to add some lines to your configuration file:

~/.zshrc
autoload -Uz add-zsh-hook

DIRSTACKFILE="${XDG_CACHE_HOME:-$HOME/.cache}/zsh/dirs"
if [[ -f "$DIRSTACKFILE" ]] && (( ${#dirstack} == 0 )); then
	dirstack=("${(@f)"$(< "$DIRSTACKFILE")"}")
	[[ -d "${dirstack[1]}" ]] && cd -- "${dirstack[1]}"
fi
chpwd_dirstack() {
	print -l -- "$PWD" "${(u)dirstack[@]}" > "$DIRSTACKFILE"
}
add-zsh-hook -Uz chpwd chpwd_dirstack

DIRSTACKSIZE='20'

setopt AUTO_PUSHD PUSHD_SILENT PUSHD_TO_HOME

## Remove duplicate entries
setopt PUSHD_IGNORE_DUPS

## This reverts the +/- operators.
setopt PUSHD_MINUS

Now use

$ dirs -v

to print the dirstack. Use cd -<NUM> to go back to a visited folder. Use autocompletion after the dash. This proves very handy if using the autocompletion menu.

Note: This will not work if you have more than one zsh session open, and attempt to cd, due to a conflict in both sessions writing to the same file.

cdr

cdr allows you to change the working directory to a previous working directory from a list maintained automatically. It stores all entries in files that are maintained across sessions and (by default) between terminal emulators in the current session.

See zshcontrib(1) for setup instructions.

Help command

Unlike Bash, Zsh does not enable a built in help command, instead it provides run-help. By default run-help is an alias to man, it can be either executed manually by prepending it to a command or it can be invoked for the currently typed command with the keyboard shortcuts Alt+h or Esc h.

Since by default it is just an alias to man, it will only work on external commands. To improve its functionality, so that it works on shell builtins and other shell features, you need to use the run-help function. See zshcontrib(1) for more information on the run-help and its assistant functions.

First load the run-help function and then remove the existing run-help alias. For convenience help can be aliased to run-help. For example, add following to your zshrc:

autoload -Uz run-help
unalias run-help
alias help=run-help

Assistant functions have to be enabled separately:

autoload -Uz run-help-git
autoload -Uz run-help-ip
autoload -Uz run-help-openssl
autoload -Uz run-help-p4
autoload -Uz run-help-sudo
autoload -Uz run-help-svk
autoload -Uz run-help-svn

For example, run-help git commit command will now open the man page git-commit(1) instead of git(1).

Persistent rehash

Typically, compinit will not automatically find new executables in the $PATH. For example, after you install a new package, the files in /usr/bin/ would not be immediately or automatically included in the completion. Thus, to have these new executables included, one would run:

$ rehash

This 'rehash' can be set to happen automatically.[4] Simply include the following in your zshrc:

~/.zshrc
zstyle ':completion:*' rehash true

On-demand rehash

As above, however pacman can be configured with hooks to automatically request a rehash, which does not incur the performance penalty of constant rehashing as above. To enable this, create the /etc/pacman.d/hooks directory, and a /var/cache/zsh directory, then create a hook file:

/etc/pacman.d/hooks/zsh.hook
[Trigger]
Operation = Install
Operation = Upgrade
Operation = Remove
Type = Path
Target = usr/bin/*
[Action]
Depends = zsh
When = PostTransaction
Exec = /usr/bin/install -Dm644 /dev/null /var/cache/zsh/pacman

This keeps the modification date of the file /var/cache/zsh/pacman consistent with the last time a package was installed, upgraded or removed. Then, zsh must be coaxed into rehashing its own command cache when it goes out of date, by adding to your ~/.zshrc:

~/.zshrc
zshcache_time="$(date +%s%N)"

autoload -Uz add-zsh-hook

rehash_precmd() {
  if [[ -a /var/cache/zsh/pacman ]]; then
    local paccache_time="$(date -r /var/cache/zsh/pacman +%s%N)"
    if (( zshcache_time < paccache_time )); then
      rehash
      zshcache_time="$paccache_time"
    fi
  fi
}

add-zsh-hook -Uz precmd rehash_precmd

If the precmd hook is triggered before /var/cache/zsh/pacman is updated, completion may not work until a new prompt is initiated. Running an empty command, e.g. pressing enter, should be sufficient.

Alternative on-demand rehash using SIGUSR1

As above, however the hook file looks like this:

/etc/pacman.d/hooks/zsh-rehash.hook
[Trigger]
Operation = Install
Operation = Upgrade
Operation = Remove
Type = Path
Target = usr/bin/*

[Action]
Depends = zsh
Depends = procps-ng
When = PostTransaction
Exec = /usr/bin/pkill zsh --signal=USR1
Warning: This sends SIGUSR1 to all running zsh instances. Note that the default behavior for SIGUSR1 is terminate so when you first configure this all running zsh instances of all users (including login shells) will terminate if they have not sourced the trap below.
~/.zshrc
catch_signal_usr1() {
  trap catch_signal_usr1 USR1
  rehash
}
trap catch_signal_usr1 USR1

This method will instantly rehash all zsh instances, removing the need to press enter to trigger precmd.

Bind key to ncurses application

Bind a ncurses application to a keystroke, but it will not accept interaction. Use BUFFER variable to make it work. The following example lets users open ncmpcpp using Alt+\:

~/.zshrc
ncmpcppShow() {
  BUFFER="ncmpcpp"
  zle accept-line
}
zle -N ncmpcppShow
bindkey '^[\' ncmpcppShow

An alternate method, that will keep everything you entered in the line before calling application:

~/.zshrc
ncmpcppShow() {
  ncmpcpp <$TTY
  zle redisplay
}
zle -N ncmpcppShow
bindkey '^[\' ncmpcppShow

File manager key binds

Key binds like those used in graphic file managers may come handy. The first comes back in directory history (Alt+Left), the second let the user go to the parent directory (Alt+Up). They also display the directory content.

~/.zshrc
cdUndoKey() {
  popd
  zle       reset-prompt
  echo
  ls
  zle       reset-prompt
}

cdParentKey() {
  pushd ..
  zle      reset-prompt
  echo
  ls
  zle       reset-prompt
}

zle -N                 cdParentKey
zle -N                 cdUndoKey
bindkey '^[[1;3A'      cdParentKey
bindkey '^[[1;3D'      cdUndoKey

xterm title

If your terminal emulator supports it, you can set its title from Zsh. This allows dynamically changing the title to display relevant information about the shell state, for example showing the user name and current directory or the currently executing command.

The xterm title is set with the xterm escape sequence \e]2;\a. For example:

$ print -n '\e]2;My xterm title\a'

will set the title to

My xterm title

A simple way to have a dynamic title is to set the title in the precmd and preexec hook functions. See zshmisc(1) for a list of available hook functions and their descriptions.

By using print -P you can additionally take advantage of Zsh's prompt escapes.

Tip:
  • Title printing can be split up in multiple commands as long as they are sequential.
  • GNU Screen sends the xterm title to the hardstatus (%h). If you want to use Screen's string escapes (e.g. for colors) you should set the hardstatus with the \e_\e\\ escape sequence. Otherwise, if string escapes are used in \e]2;\a, the terminal emulator will get a garbled title due to it being incapable of interpreting Screen's string escapes.
Note:
  • Do not use the -P option of print when printing variables to prevent them from being parsed as prompt escapes.
  • Use the q parameter expansion flag when printing variables to prevent them from being parsed as escape sequences.
~/.zshrc
autoload -Uz add-zsh-hook

function xterm_title_precmd () {
	print -Pn -- '\e]2;%n@%m %~\a'
	[[ "$TERM" == 'screen'* ]] && print -Pn -- '\e_\005{g}%n\005{-}@\005{m}%m\005{-} \005{B}%~\005{-}\e\\'
}

function xterm_title_preexec () {
	print -Pn -- '\e]2;%n@%m %~ %# ' && print -n -- "${(q)1}\a"
	[[ "$TERM" == 'screen'* ]] && { print -Pn -- '\e_\005{g}%n\005{-}@\005{m}%m\005{-} \005{B}%~\005{-} %# ' && print -n -- "${(q)1}\e\\"; }
}

if [[ "$TERM" == (alacritty*|gnome*|konsole*|putty*|rxvt*|screen*|tmux*|xterm*) ]]; then
	add-zsh-hook -Uz precmd xterm_title_precmd
	add-zsh-hook -Uz preexec xterm_title_preexec
fi

Terminal emulator tab title

Some terminal emulators and multiplexers support setting the title of the tab. The escape sequences depend on the terminal:

Terminal Escape sequences Description
GNU Screen \ek\e\\ Screen's window title (%t).
Konsole \e]30;\a Konsole's tab title.

Shell environment detection

See a repository about shell environment detection for tests to detect the shell environment. This includes login/interactive shell, Xorg session, TTY and SSH session.

/dev/tcp equivalent: ztcp

Use the zsh/net/tcp module:

$ zmodload zsh/net/tcp

You can now establish TCP connections:

$ ztcp example.com 80

Shortcut to exit shell on partial command line

By default, Ctrl+d will not close your shell if the command line is filled, this fixes it:

.zshrc
exit_zsh() { exit }
zle -N exit_zsh
bindkey '^D' exit_zsh

Third-party extensions

Configuration frameworks

  • oh-my-zsh — A popular, community-driven framework for managing your Zsh configuration. It comes bundled with a ton of helpful functions, helpers, plugins, themes.
https://github.com/robbyrussell/oh-my-zsh || oh-my-zsh-gitAUR
  • Prezto — A configuration framework for Zsh. It comes with modules, enriching the command line interface environment with sane defaults, aliases, functions, auto completion, and prompt themes.
https://github.com/sorin-ionescu/prezto || prezto-gitAUR
  • ZIM — A configuration framework with blazing speed and modular extensions. Zim is very easy to customize, and comes with a rich set of modules and features without compromising on speed or functionality.
https://github.com/zimfw/zimfw || zsh-zim-gitAUR

Plugin managers

  • Antibody — A performance-focused plugin manager similar to Antigen.
https://github.com/getantibody/antibody || antibodyAUR
  • zinit (previously "zplugin") — Flexible Zsh plugin manager with clean fpath, reports, completion management, turbo mode
http://github.com/zdharma/zinit || zsh-zplugin-gitAUR
  • Antigen — A plugin manager for Zsh, inspired by oh-my-zsh and vundle. ABANDONED
https://github.com/zsh-users/antigen || antigen-gitAUR
  • zgen — A lightweight and simple plugin manager for Zsh. ABANDONED
https://github.com/tarjoilija/zgen || zgen-gitAUR
  • zplug — A next-generation plugin manager for Zsh. ABANDONED
https://github.com/zplug/zplug || zplugAUR

Fish-like syntax highlighting

Fish provides a very powerful shell syntax highlighting. To use this in Zsh, you can install zsh-syntax-highlighting and source the provided script from your zshrc:

source /usr/share/zsh/plugins/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh

The "command not found" handler

pkgfile includes a Zsh script file that provides a command_not_found_handler function that will automatically search the official repositories, when entering an unrecognized command.

You need to source the script to enable it. For example:

~/.zshrc
source /usr/share/doc/pkgfile/command-not-found.zsh
Note: The pkgfile database may need to be updated before this will work. See pkgfile#Installation for details.

Uninstallation

Change the default shell before removing the zsh package.

Warning: Failure to follow the below procedure may result in users no longer having access to a working shell.

Run following command:

$ chsh -s /bin/bash user

Use it for every user with zsh set as their login shell (including root if needed). When completed, the zsh package can be removed.

Alternatively, change the default shell back to Bash by editing /etc/passwd as root.

Warning: It is strongly recommended to use vipw(8) when editing /etc/passwd as it helps prevent invalid entries and/or syntax errors.

For example, change the following:

username:x:1000:1000:Full Name,,,:/home/username:/bin/zsh

To this:

username:x:1000:1000:Full Name,,,:/home/username:/bin/bash

See also