Difference between revisions of "Zsh"

From ArchWiki
Jump to: navigation, search
(Alternative method without using terminfo)
m (use https for grml.org links)
 
(156 intermediate revisions by 58 users not shown)
Line 2: Line 2:
 
[[cs:Zsh]]
 
[[cs:Zsh]]
 
[[de:Zsh]]
 
[[de:Zsh]]
 +
[[es:Zsh]]
 
[[fr:Zsh]]
 
[[fr:Zsh]]
 +
[[ja:Zsh]]
 +
[[ru:Zsh]]
 
[[zh-CN:Zsh]]
 
[[zh-CN:Zsh]]
[http://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 [[Bash]] (not by default, only if you issue "emulate sh"), it offers many advantages such as:
+
[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].
  
* Faster
+
The [http://zsh.sourceforge.net/FAQ/zshfaq01.html#l4 Zsh FAQ] offers more reasons to use Zsh.
* Improved tab completion
+
* Improved globbing
+
* Improved array handling
+
* Fully customisable
+
 
+
The Zsh FAQ offers [http://zsh.sourceforge.net/FAQ/zshfaq01.html#l4 more reasons] to use Zsh as your shell.
+
  
 
== Installation ==
 
== Installation ==
  
Before starting you 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
  
[[pacman|Install]] the {{Pkg|zsh}} package available in the [[official repositories]].
+
[[Install]] the {{Pkg|zsh}} package. For additional completion definitions, install the {{pkg|zsh-completions}} package as well.
  
 
=== Initial configuration ===
 
=== Initial configuration ===
Line 28: Line 25:
 
  $ 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}}.
+
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
  
 
=== Making Zsh your default shell ===
 
=== Making Zsh your default shell ===
  
If the shell is listed in {{ic|/etc/shells}} you can use the {{ic|chsh}} command to change your default shell without root access. If you installed Zsh from the [[Official Repositories|official repositories]], it should already have an entry in {{ic|/etc/shells}}.
+
See [[Command-line shell#Changing your default shell]].
  
Change the default shell for the current user:
+
{{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]]).}}
  
$ chsh -s $(which zsh)
+
== Startup/Shutdown files ==
  
{{Note|You have to log out and log back in, in order to start using Zsh as your default shell.}}
+
{{Note|
 
+
* If {{ic|$ZDOTDIR}} is not set, {{ic|$HOME}} is used instead.
After logging back in, you should notice Zsh's prompt, which by default looks different from Bash's. However you can verify that Zsh is the current shell by issuing:
+
* If option {{ic|RCS}} is unset in any of the files, no configuration files 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 sourced after that file.
$ echo $SHELL
+
}}
 
+
{{Tip|If you are replacing {{Pkg|bash}}, you 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. [[Start X at Boot|the code that starts your X Window System]]).}}
+
 
+
== Configuration files ==
+
 
+
At login, Zsh sources the following files in this order:
+
;{{ic|~/.zshenv}}:This file should contain commands to set the [[#Configuring $PATH|command search path]], plus other important environment variables; it should not contain commands that produce output or assume the shell is attached to a tty.
+
;{{ic|/etc/profile}}:This file is sourced by all Bourne-compatible shells upon login: it sets up an environment upon login and application-specific ({{ic|/etc/profile.d/*.sh}}) settings.
+
;{{ic|~/.zprofile}}:This file is generally used for automatic execution of user's scripts.
+
;{{ic|~/.zshrc}}:This is Zsh's main configuration file.
+
;{{ic|~/.zlogin}}:This file is generally used for automatic execution of user's scripts.
+
  
At logout it sources '''{{ic|~/.zlogout}}''', which is used for automatic execution of user's scripts.
+
When starting Zsh, it'll source 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|$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|/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/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|$ZDOTDIR/.zprofile}}:Used for executing user's commands at start, will be sourced when starting as a '''''login shell'''''.
 +
;{{ic|/etc/zsh/zshrc}}:Used for setting interactive shell configuration and executing commands, will be sourced when starting as a '''''interactive shell'''''.
 +
;{{ic|$ZDOTDIR/.zshrc}}:Used for setting user's interactive shell configuration and executing commands, will be sourced when starting as a '''''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|$ZDOTDIR/.zlogin}}:Used for executing user's commands at ending of initial progress, will be sourced when starting as a '''''login shell'''''.
 +
;{{ic|$ZDOTDIR/.zlogout}}:Will be sourced when a '''''login shell''''' '''exits'''.
 +
;{{ic|/etc/zsh/zlogout}}:Will be sourced when a '''''login shell''''' '''exits'''.
  
 
{{Note|
 
{{Note|
* The paths used in Arch's {{Pkg|zsh}} package are different from the default ones used in the man pages.
+
* The paths used in Arch's {{Pkg|zsh}} package are different from the default ones used in the [[man page]]s ({{Bug|48992}})
* {{ic|$ZDOTDIR}} defaults to {{ic|$HOME}}
+
* {{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 set the {{ic|$PATH}} variable in {{ic|$ZDOTDIR/.zprofile}}
* {{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|~/.zshenv}}. To prevent this, either replace the {{ic|/etc/zsh/zprofile}} file with your own, or set your {{ic|$PATH}} variable from {{ic|~/.zshrc}}.
+
 
}}
 
}}
 +
{{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'll break the integrality of other packages which provide some scripts in {{ic|/etc/profile.d}}}}
  
== ~/.zshrc configuration ==
+
== Configure Zsh ==
  
Although Zsh is usable out of the box, it is almost certainly not set up the way you would like to use it, but due to the sheer amount of customisation available in Zsh, configuring Zsh can be a daunting and time-consuming experience.
+
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.
  
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 customised. In order to use this configuration save it as a file named {{ic|.zshrc}}. You can then apply the changes without needing to logout and then back in by running:
+
=== Simple .zshrc ===
  
$ source ~/.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 {{ic|.zshrc}}.
  
=== Simple .zshrc ===
+
{{Tip|Apply the changes without needing to logout and then back in by running {{ic|source ~/.zshrc}}}}
  
Here is a simple {{ic|.zshrc}}, that should be sufficient to get you started:
+
Here is a simple {{ic|.zshrc}}:
  
 
{{hc|~/.zshrc|
 
{{hc|~/.zshrc|
autoload -U compinit promptinit
+
autoload -Uz compinit promptinit
 
compinit
 
compinit
 
promptinit
 
promptinit
Line 85: Line 84:
 
=== Configuring $PATH ===
 
=== Configuring $PATH ===
  
Information about setting up the system path per user in zsh can be found here: http://zsh.sourceforge.net/Guide/zshguide02.html#l24
+
Normally, the path should be set in {{ic|~/.zshenv}}, but Arch Linux sources {{ic|/etc/profile}} after sourcing {{ic|~/.zshenv}}.
  
In short, put the following in your {{ic|~/.zshenv}}:
+
To prevent your $PATH being overwritten, set it in {{ic|~/.zprofile}}.
{{hc|~/.zshenv|
+
 
 +
{{hc|~/.zprofile|
 
typeset -U path
 
typeset -U path
path=(~/bin /other/things/in/path $path)}}
+
path=(~/bin /other/things/in/path $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 ===
  
Perhaps the most compelling feature of Zsh is its advanced autocompletion abilities. At the very least, you will want to enable autocompletion in your {{ic|.zshrc}}. To enable autocompletion, add the following to:
+
Perhaps the most compelling feature of Zsh is its advanced autocompletion abilities. At the very least, enable autocompletion in {{ic|.zshrc}}. To enable autocompletion, add the following to your {{ic|~/.zshrc}}:
  
 
{{hc|~/.zshrc|
 
{{hc|~/.zshrc|
autoload -U compinit
+
autoload -Uz compinit
compinit}}
+
compinit
 +
}}
  
The above configuration includes ssh/scp/sftp hostnames completion but in order for this feature to work you will 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 need to prevent ssh from hashing hosts names in {{ic|~/.ssh/known_hosts}}.
{{Warning|This makes your computer vulnerable to [http://nms.lcs.mit.edu/projects/ssh/README.hashed-hosts "Island-hopping" attacks]. In that intention, comment the following line or set the value to {{ıc|no}}:
+
{{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|
 
{{hc|/etc/ssh/ssh_config|
 
#HashKnownHosts yes}}
 
#HashKnownHosts yes}}
And move your {{ic|~/.ssh/known_hosts}} somewhere else so that ssh creates a new one with un-hashed hostnames (previously known hosts will thus be lost).
+
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].
 
}}
 
}}
  
Line 114: Line 117:
 
For autocompletion of command line switches for aliases, add the following to:
 
For autocompletion of command line switches for aliases, add the following to:
 
{{hc|~/.zshrc|
 
{{hc|~/.zshrc|
setopt completealiases}}
+
setopt COMPLETE_ALIASES}}
 +
 
 +
=== Autostart X at login ===
 +
See [[Xinitrc#Autostart X at login]].
  
 
=== The "command not found" hook ===
 
=== The "command not found" hook ===
  
The [[pkgfile]] package includes a "command not found" hook that will automatically search the [[official repositories]] when you enter an unrecognized command. Then it will display something like this:
+
See [[Pkgfile#Command not found]].
  
{{hc|$ abiword|
+
=== The ttyctl command ===
abiword may be found in the following packages:
+
  extra/abiword 2.8.6-7 usr/bin/abiword
+
}}
+
  
Load pkgfile with the following:
+
[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|
source /usr/share/doc/pkgfile/command-not-found.zsh
+
ttyctl -f}}
}}
+
   
 
+
An alternative "command not found" hook is also provided by the AUR package [https://aur.archlinux.org/packages.php?ID=52305 command-not-found], which will generate an output like the following:
+
 
+
{{hc|$ abiword|
+
The command 'abiword' is been provided by the following packages:
+
'''abiword''' (2.8.6-7) from extra
+
[ abiword ]
+
'''abiword''' (2.8.6-7) from staging
+
[ abiword ]
+
'''abiword''' (2.8.6-7) from testing
+
[ abiword ]
+
}}
+
 
+
for it to work, add the following to a zshrc:
+
 
+
  [ -r /etc/profile.d/cnf.sh ] && . /etc/profile.d/cnf.sh
+
 
+
=== Prevent from putting duplicate lines in the history ===
+
 
+
It is very convinient to ignore duplicate lines in the history. To do so, put the following:
+
{{hc|~/.zshrc|
+
setopt HIST_IGNORE_DUPS}}
+
 
+
 
=== Key bindings ===
 
=== Key bindings ===
  
 
Zsh does not use readline, instead it uses its own and more powerful zle. It does not read {{ic|/etc/inputrc}} or {{ic|~/.inputrc}}.
 
Zsh does not use readline, instead it uses its own and more powerful zle. It does not read {{ic|/etc/inputrc}} or {{ic|~/.inputrc}}.
zle has an [[emacs]] mode and a [[vi]] mode. By default, it tries to guess whether you want emacs or vi keys from the {{ic|$EDITOR}} environment variable. If it is empty, it will default to emacs. You can change this with {{ic|bindkey -v}} or {{ic|bindkey -e}}.
+
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.
  
To get some special keys working:
+
See also [http://zshwiki.org/home/zle/bindkeys zshwiki: bindkeys].
{{hc|~/.zshrc|2=
+
# create a zkbd compatible hash;
+
# to add other keys to this hash, see: man 5 terminfo
+
typeset -A key
+
  
key[Home]=${terminfo[khome]}
+
==== Bind key to ncurses application ====
  
key[End]=${terminfo[kend]}
+
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+\}}:
key[Insert]=${terminfo[kich1]}
+
{{hc|~/.zshrc|2=
key[Delete]=${terminfo[kdch1]}
+
ncmpcppShow() { BUFFER="ncmpcpp"; zle accept-line; }
key[Up]=${terminfo[kcuu1]}
+
zle -N ncmpcppShow
key[Down]=${terminfo[kcud1]}
+
bindkey '^[\' ncmpcppShow
key[Left]=${terminfo[kcub1]}
+
}}
key[Right]=${terminfo[kcuf1]}
+
key[PageUp]=${terminfo[kpp]}
+
key[PageDown]=${terminfo[knp]}
+
  
# setup key accordingly
+
==== Alternate way to bind ncurses application ====
[[ -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[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
+
  
# Finally, make sure the terminal is in application mode, when zle is
+
This method will keep everything you entered in the line before calling application
# active. Only then are the values from $terminfo valid.
+
{{hc|~/.zshrc|2=
if (( ${+terminfo[smkx]} )) && (( ${+terminfo[rmkx]} )); then
+
ncmpcppShow() { ncmpcpp <$TTY; zle redisplay; }
    function zle-line-init () {
+
zle -N ncmpcppShow
        printf '%s' "${terminfo[smkx]}"
+
bindkey '^[\' ncmpcppShow
    }
+
    function zle-line-finish () {
+
        printf '%s' "${terminfo[rmkx]}"
+
    }
+
    zle -N zle-line-init
+
    zle -N zle-line-finish
+
fi
+
 
}}
 
}}
  
{{Note|To get the proper sequences for certain key combinations, start {{ic|cat}} or {{ic|read}} without any parameters and press them; they should then be printed in the terminal. Both can be closed again via {{ic|Ctrl+c}}.}}
+
==== File manager key binds ====
  
==== Alternative method without using terminfo ====
+
Key binds like those used in graphic file managers may come handy. The first comes back in directory history ({{ic|Alt+Left}}), the second let the user go to the parent directory ({{ic|Alt+Up}}). They also display the directory content.
  
Run {{ic|autoload zkbd}} followed by just {{ic|zkbd}}. If you can't press the key it asks for (e.g.  {{ic|F11}} maximizes the window), press space to skip it. After finishing with zkbd, add the following to your {{ic|~/.zshrc}}:
+
{{hc|~/.zshrc|<nowiki>
 +
cdUndoKey() {
 +
  popd      > /dev/null
 +
  zle      reset-prompt
 +
  echo
 +
  ls
 +
  echo
 +
}
  
{{hc|~/.zshrc|autoload zkbd
+
cdParentKey() {
source ~/.zkbd/$TERM-:0.0 # may be different - check where zkbd saved yours
+
  pushd .. > /dev/null
 +
  zle      reset-prompt
 +
  echo
 +
  ls
 +
  echo
 +
}
  
[[ -n ${key[Backspace]} ]] && bindkey "${key[Backspace]}" backward-delete-char
+
zle -N                cdParentKey
[[ -n ${key[Insert]} ]] && bindkey "${key[Insert]}" overwrite-mode
+
zle -N                cdUndoKey
[[ -n ${key[Home]} ]] && bindkey "${key[Home]}" beginning-of-line
+
bindkey '^[[1;3A'      cdParentKey
[[ -n ${key[PageUp]} ]] && bindkey "${key[PageUp]}" up-line-or-history
+
bindkey '^[[1;3D'     cdUndoKey
[[ -n ${key[Delete]} ]] && bindkey "${key[Delete]}" delete-char
+
</nowiki>}}
[[ -n ${key[End]} ]] && bindkey "${key[End]}" end-of-line
+
[[ -n ${key[PageDown]} ]] && bindkey "${key[PageDown]}" down-line-or-history
+
[[ -n ${key[Up]} ]] && bindkey "${key[Up]}" up-line-or-search
+
[[ -n ${key[Left]} ]] && bindkey "${key[Left]}" backward-char
+
[[ -n ${key[Down]} ]] && bindkey "${key[Down]}" down-line-or-search
+
[[ -n ${key[Right]} ]] && bindkey "${key[Right]}" forward-char
+
}}
+
 
+
==== Bind key to ncurses application ====
+
 
+
You can 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 you open ncmpcpp using {{ic|Alt+\}}:
+
{{hc|~/.zshrc|2=
+
ncmpcppShow() { BUFFER="ncmpcpp"; zle accept-line; }
+
zle -N ncmpcppShow
+
bindkey '^[\' ncmpcppShow
+
}}
+
  
 
=== History search ===
 
=== History search ===
  
You can add these lines to your .zshrc
+
Add these lines to .zshrc
  
 
{{hc|~/.zshrc|<nowiki>
 
{{hc|~/.zshrc|<nowiki>
[[ -n "${key[PageUp]}"  ]] && bindkey "${key[PageUp]}"   history-beginning-search-backward
+
autoload -Uz up-line-or-beginning-search down-line-or-beginning-search
[[ -n "${key[PageDown]}" ]] && bindkey "${key[PageDown]}" history-beginning-search-forward
+
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
 
</nowiki>}}
 
</nowiki>}}
  
Doing this, only past commands beginning with the current input would have been shown.
+
Doing this, only past commands matching the current line up to the current cursor position will be shown.
  
 
=== Prompts ===
 
=== Prompts ===
  
There is a quick and easy way to set up a colored prompt in Zsh. Make sure that prompt is set to autoload in your {{ic|.zshrc}}. This can be done by adding these lines to:
+
==== 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:
  
 
{{hc|~/.zshrc|
 
{{hc|~/.zshrc|
autoload -U promptinit
+
autoload -Uz promptinit
 
promptinit
 
promptinit
 
}}
 
}}
  
You can now see available prompts by running the command:
+
Available prompt themes are listed by running the command:
+
 
 
  $ prompt -l
 
  $ prompt -l
  
To try one of the commands that is listed, use the command prompt followed by the name of the prompt you like. For example, to use the {{ic|walters}} prompt, you would enter:
+
For example, to use the {{ic|walters}} theme, enter:
  
 
  $ prompt walters
 
  $ prompt walters
  
To preview all available themes you could use this command:
+
To preview all available themes, use this command:
  
 
  $ prompt -p
 
  $ prompt -p
  
=== Customizing your prompt ===
+
==== Customized prompt ====
  
In case you are dissatisfied with the prompts mentioned above(or want to expand their usefulness), Zsh offers the possibility to build your own custom prompt. Zsh supports a left- and right-sided prompt additional to the single, left-sided prompt that is common to all shells. You can customize it by using {{ic|1=PROMPT=}} with the following variables:
+
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.
  
==== Prompt variables ====
+
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 zshmisc(1) manpage.
 
+
===== General =====
+
 
+
; %n : The username
+
; %m : The computer's hostname(truncated to the first period)
+
; %M : The computer's hostname
+
; %l : The current tty
+
; %? : The return code of the last-run application.
+
; %# : The prompt based on user privileges ({{ic|#}} for root and {{ic|%}} for the rest)
+
 
+
===== Times =====
+
 
+
; %T : System time(HH:MM)
+
; %* : System time(HH:MM:SS)
+
; %D : System date(YY-MM-DD)
+
 
+
===== Directories =====
+
 
+
; %~ : The current working directory. If you are in you are in your {{ic|$HOME}}, this will be replaced by {{ic|~}}.
+
; %d : The current working directory.
+
 
+
For the options mentioned above: You can prefix an integer to show only certain parts of your working path. If you entered {{ic|%1d}} and found yourself in {{ic|/usr/bin}} it would show {{ic|bin}}. This can also be done with negative integers:
+
{{ic|%-1d}} using the same directory as above would show {{ic|/}}.
+
 
+
===== Formatting =====
+
 
+
; %U [...] %u : Begin and end underlined print
+
; %B [...] %b : Begin and end bold print
+
; %{ [...] %} : Begin and enter area that will not be printed. Useful for setting colors.
+
:In fact, this tag forces Zsh to ignore anything inside them when making indents for the prompt as well.
+
:As such, not to use it can have some weird effects on the margins and indentation of the prompt.
+
  
 
===== Colors =====
 
===== Colors =====
  
Zsh has a different approach to setting colors on the terminal than the one depicted [https://wiki.archlinux.org/index.php/Color_Bash_Prompt here]. First you write before {{ic|1=PROMPT=}} in your {{ic|.zshrc}}:
+
Zsh sets colors differently than [[Color_Bash_Prompt|Bash]]. Add {{ic|autoload -Uz colors && colors}} before {{ic|1=PROMPT=}} in {{ic|.zshrc}} to use them. Usually you will want to put these inside {{ic|%{ [...] %} }} so the cursor does not move.
autoload -U colors && colors
+
  
Following commands would now produce the color escape sequence needed to set the requested color when the prompt is printed:
+
{| class="wikitable"
; $fg[color] : will set the text color (red, green, blue, etc. - defaults to bold)
+
! Command !! Description
; $fg_no_bold[color]: will set the non-bold text color
+
|-
; $fg_bold[color]: will set the bold text color
+
| {{ic|$fg[color]}} || will set the text color (red, green, blue, etc. - defaults to whatever format set prior to text)
; $reset_color : will reset the text color to the default color
+
|-
It is useful to put these color commands inside {{ic|%{ [...] %} }}, so the shell knows there is no output from these sequences and the cursor hasn't moved.
+
| {{ic|%F{color} [...] %f}} || effectively the same as the previous, but with less typing. Can also prefix F with a number instead.
 +
|-
 +
| {{ic|$fg_no_bold[color]}} || will set text to non-bold and set the text color
 +
|-
 +
| {{ic|$fg_bold[color]}} || will set the text to bold and set the text color
 +
|-
 +
| {{ic|$reset_color}} || will reset the text color to the default color. Does not reset bold. use {{ic|%b}} to reset bold. Saves typing if it's just {{ic|%f}} though.
 +
|-
 +
| {{ic|%K{color} [...] %k}} || will set the background color. Same color as non-bold text color. Prefixing with any single-digit number makes the bg black.
 +
|-
 +
| {{ic|%S [...] %s}} || Standout mode, switches the text and background colors. Useful for Powerline-like prompts, especially if you switch between light/dark backgrounds.
 +
|}
  
;Possible color values
+
{| class="wikitable"
{| border="1"
+
 
|-
 
|-
|black || red
+
! colspan="2" | Possible color values
 
|-
 
|-
|green || yellow
+
| {{ic|black}} or {{ic|0}} || {{ic|red}} or {{ic|1}}
 
|-
 
|-
|blue || magenta
+
| {{ic|green}} or {{ic|2}} || {{ic|yellow}} or {{ic|3}}
 
|-
 
|-
|cyan || white
+
| {{ic|blue}} or {{ic|4}} || {{ic|magenta}} or {{ic|5}}
 
|-
 
|-
 +
| {{ic|cyan}} or {{ic|6}} || {{ic|white}} or {{ic|7}}
 
|}
 
|}
Note that bold text doesn't necessarily use the same colors as normal text. For example, $fg['yellow'] looks brown or a very dark yellow, while $fg_no_bold['yellow'] looks like bright or regular yellow.
 
  
==== Example ====
+
{{Note| Bold text does not necessarily use the same colors as normal text. For example, {{ic|$fg['yellow']}} looks brown or a very dark yellow, while {{ic|$fg_bold['yellow']}} looks like bright or regular yellow.}}
 +
 
 +
===== Example =====
 +
 
 +
This is an example of a two-sided prompt:
  
To have a two-sided prompt you could write:
+
  PROMPT="%{$fg[red]%}%n%{$reset_color%}@%{$fg[blue]%}%m %{$fg_no_bold[yellow]%}%1~ %{$reset_color%}%# "
  PROMPT="%{$fg[red]%}%n%{$reset_color%}@%{$fg[blue]%}%m %{$fg_no_bold[yellow]%}%1~ %{$reset_color%}%#"
+
 
  RPROMPT="[%{$fg_no_bold[yellow]%}%?%{$reset_color%}]"
 
  RPROMPT="[%{$fg_no_bold[yellow]%}%?%{$reset_color%}]"
  
It would equal(without colors):
+
And here's how it will be displayed:
 +
 
 
  username@host ~ %                                                        [0]
 
  username@host ~ %                                                        [0]
  
=== Dirstack ===
+
=== Remembering recent directories ===
  
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 you configuration file:
+
==== 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:
  
 
{{hc|.zshrc|<nowiki>
 
{{hc|.zshrc|<nowiki>
Line 353: Line 298:
 
DIRSTACKSIZE=20
 
DIRSTACKSIZE=20
  
setopt autopushd pushdsilent pushdtohome
+
setopt AUTO_PUSHD PUSHD_SILENT PUSHD_TO_HOME
  
 
## Remove duplicate entries
 
## Remove duplicate entries
setopt pushdignoredups
+
setopt PUSHD_IGNORE_DUPS
  
 
## This reverts the +/- operators.
 
## This reverts the +/- operators.
setopt pushdminus
+
setopt PUSHD_MINUS
 
</nowiki>}}
 
</nowiki>}}
  
Now you can use
+
Now use
  dirs -v
+
  $ dirs -v
to print the dirstack. Use {{ic|cd -<NUM>}} to go back to a visited folder. You can use autocompletion after the dash. This proves very handy if you are using the autocompletion menu.
+
to print the dirstack. Use {{ic|cd -<NUM>}} to go back to a visited folder. Use autocompletion after the dash. This proves very handy if using the autocompletion menu.
  
=== Sample .zshrc files ===
+
{{Note|This will not work if you have more than one ''zsh'' session open, and attempt to {{ic|cd}}, due to a conflict in both sessions writing to the same file.}}
  
Here is a list of {{ic|.zshrc}} files. Feel free to add your own:
+
==== cdr ====
  
* [https://github.com/sorin-ionescu/prezto Prezto - Instantly Awesome Zsh] (AUR package: {{AUR|prezto-git}}) is 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.
+
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.
 +
To use cdr add the following lines to shell configuration:
 +
{{hc|.zshrc|
 +
autoload -Uz chpwd_recent_dirs cdr add-zsh-hook
 +
add-zsh-hook chpwd chpwd_recent_dirs
 +
}}
 +
 
 +
Recent directories list by default is stored in {{ic|${ZDOTDIR:-$HOME}/.chpwd-recent-dirs}}, to change it use {{ic|zstyle}}:
 +
zstyle ':chpwd:*' recent-dirs-file "${XDG_CACHE_HOME:-$HOME/.cache}/zsh/chpwd-recent-dirs"
 +
 
 +
Every time you change directory interactively, no matter which command you use, the directory to which you change will be remembered in most-recent-first order.
 +
 
 +
To print the list of recent directories use:
 +
$ cdr -l
 +
 
 +
Use {{ic|cdr <NUM>}} to go back to a visited folder. Completion for the argument to cdr is available if compinit has been run; menu selection is recommended.
 +
 
 +
=== Help command ===
 +
Unlike [[bash]], ''zsh'' does not enable a built in {{ic|help}} command. To use {{ic|help}} in zsh, add following to your {{ic|zshrc}}:
 +
 
 +
{{bc|1=
 +
autoload -Uz run-help
 +
autoload -Uz run-help-git
 +
autoload -Uz run-help-svn
 +
autoload -Uz run-help-svk
 +
unalias run-help
 +
alias help=run-help
 +
}}
 +
 
 +
=== 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:
 +
{{bc|
 +
source /usr/share/zsh/plugins/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh
 +
}}
 +
 
 +
=== 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].
 
* Basic setup, with dynamic prompt and window title/hardinfo => http://github.com/MrElendig/dotfiles-alice/blob/master/.zshrc;
 
* Basic setup, with dynamic prompt and window title/hardinfo => http://github.com/MrElendig/dotfiles-alice/blob/master/.zshrc;
* An Arch package named [https://www.archlinux.org/packages/extra/any/grml-zsh-config/ grml-zsh-config] comes from http://grml.org/zsh and provides a zshrc file that includes many tweaks for your Zshell.
+
* 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/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 wnat 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.
+
  
== Global configuration ==
+
See [[Dotfiles#Repositories]] for more.
  
Occasionally you might want to have some settings applied globally to all Zsh users. The Zsh wiki tells us that there are some global configuration files, for example {{ic|/etc/zshrc}}. This however is slightly different on ArchLinux, since it has been compiled with flags specifically to target {{ic|/etc/zsh/}} instead.
+
=== Configuration Frameworks ===
 +
{{Style|List needs to be changed to [[Template:App]].}}
  
So, for global configuration use {{ic|/etc/zsh/zshrc}}, not {{ic|/etc/zshrc}}. The same goes for {{ic|/etc/zsh/zshenv}}, {{ic|/etc/zsh/zlogin}} and {{ic|/etc/zsh/zlogout}}. Note that these files are not installed by default, so you need to create them yourself if you want to use them.
+
* [https://github.com/zsh-users/antigen Antigen] (available as {{AUR|antigen-git}})  - A plugin manager for zsh, inspired by oh-my-zsh and vundle.
 +
* [https://github.com/robbyrussell/oh-my-zsh oh-my-zsh] is 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/sorin-ionescu/prezto Prezto - Instantly Awesome Zsh] (available as {{AUR|prezto-git}}) is 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.
  
The only exception is zprofile, use {{ic|/etc/profile}} instead.
+
=== Persistent rehash ===
  
=== Autostarting applications ===
+
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 exectuables included, one would run:
 +
$ rehash
  
Zsh always executes {{ic|/etc/zsh/zshenv}} and {{ic|$ZDOTDIR/.zshenv}} so do not bloat these files.
+
This 'rehash' can be set to happen automatically. Simply include the following in your {{ic|zshrc}}:
  
If the shell is a login shell, commands are read from {{ic|/etc/profile}} and then {{ic|$ZDOTDIR/.zprofile}}. Then, if the shell is interactive, commands are read from {{ic|/etc/zsh/zshrc}} and then {{ic|$ZDOTDIR/.zshrc}}. Finally, if the shell is a login shell, {{ic|/etc/zsh/zlogin}} and {{ic|$ZDOTDIR/.zlogin}} are read.
+
{{hc|~/.zshrc|zstyle ':completion:*' rehash true}}
  
See also the ''STARTUP/SHUTDOWN FILES'' section of {{ic|man zsh}}.
+
{{Note|This hack has been found in a PR for Oh My Zsh [https://github.com/robbyrussell/oh-my-zsh/issues/3440]}}
  
 
== Uninstallation ==
 
== Uninstallation ==
  
If you decide that Zsh is not the shell for you and you want to return to Bash, you must first change the default shell, before removing the Zsh package.
+
Change the default shell before removing the {{Pkg|zsh}} package.
  
{{Warning|Failure to follow the below procedures will result in all kinds of problems.}}
+
{{Warning|Failure to follow the below procedure may result in users no longer having access to a working shell.}}
  
Paste the following command in terminal as root:
+
Run following command:
# chsh -s /bin/bash user
+
Use it for every user using Zsh.
+
  
Now you can safely remove the Zsh package.
+
$ chsh -s /bin/bash ''user''
  
If you did not follow the above, you can still change the default shell back to Bash by editing {{ic|/etc/passwd}} as root.  
+
Use it for every user with ''zsh'' set as their login shell (including root if needed). When completed, the {{Pkg|zsh}} package can be removed.
  
{{Warning|It is '''strongly''' recommended to use vipw when editing user information as it prevents badly formatted entries.}}
+
Alternatively, change the default shell back to Bash by editing {{ic|/etc/passwd}} as root.
  
For example:
+
{{Warning|It is strongly recommended to use {{ic|vipw}} when editing {{ic|/etc/passwd}} as it helps prevent invalid entries and/or syntax errors.}}
  
from:
+
For example, change the following:
  ''username'':x:1000:1000:Full Name,,,:/home/''username'':/bin/zsh
+
 
to:
+
  ''username'':x:1000:1000:''Full Name'',,,:/home/''username'':/bin/zsh
  ''username'':x:1000:1000:Full Name,,,:/home/''username'':/bin/bash
+
 
 +
To this:
 +
 
 +
  ''username'':x:1000:1000:''Full Name'',,,:/home/''username'':/bin/bash
  
 
== See also ==
 
== See also ==
  
*[http://zsh.sourceforge.net/Intro/intro_1.html#SEC1 Zsh introduction]
+
*[http://zsh.sourceforge.net/Guide/zshguide.html A User's Guide to ZSH]
*[http://zsh.sourceforge.net/Guide/zshguide.html Users guide]
+
*[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 Zsh Docs] (you can choose a different format for the doc in http://zsh.sourceforge.net/Doc/)
+
 
*[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|url=https://grml.org/zsh/zsh-lovers.html}} (available as {{pkg|zsh-lovers}} package)
*[http://grml.org/zsh/zsh-lovers.html Zsh-lovers]
+
*[http://zshwiki.org/home/ Zsh Wiki]
 +
*[https://wiki.gentoo.org/wiki/Zsh/HOWTO Gentoo Wiki: Zsh/HOWTO]
 
*[http://www.bash2zsh.com/zsh_refcard/refcard.pdf Bash2Zsh Reference Card]
 
*[http://www.bash2zsh.com/zsh_refcard/refcard.pdf Bash2Zsh Reference Card]
*[https://github.com/robbyrussell/oh-my-zsh Oh My Zshell by Robby Russell]
 
*[http://www.gentoo.org/doc/en/zsh.xml Gentoo Linux Documentation -- Zsh configuration and installation guide]
 
*[http://my.opera.com/blackbelt_jones/blog/2007/06/05/zsh-prompt-configuration-issue-solved Setting up the Zsh prompt]
 
 
*'''IRC channel''': #zsh at irc.freenode.org
 

Latest revision as of 18:28, 17 August 2016

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 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

$ zsh /usr/share/zsh/functions/Newuser/zsh-newuser-install -f

Making Zsh your default shell

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

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 sourced after that file.
  • If option GLOBAL_RCS is unset in any of the files, no global configuration files (/etc/zsh/*) will be sourced after that file.

When starting Zsh, it'll source the following files in this order by default:

/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.
$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.
/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 one line which source the /etc/profile.
/etc/profile
This file should be sourced by all Bourne-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 sourced when starting as a login shell.
/etc/zsh/zshrc
Used for setting interactive shell configuration and executing commands, will be sourced when starting as a interactive shell.
$ZDOTDIR/.zshrc
Used for setting user's interactive shell configuration and executing commands, will be sourced when starting as a interactive shell.
/etc/zsh/zlogin
Used for executing commands at ending of initial progress, will be sourced when starting as a login shell.
$ZDOTDIR/.zlogin
Used for executing user's commands at ending of initial progress, will be sourced when starting as a login shell.
$ZDOTDIR/.zlogout
Will be sourced when a login shell exits.
/etc/zsh/zlogout
Will be sourced when a login shell exits.
Note:
  • The paths used in Arch's zsh package are different from the default ones used in the man pages (FS#48992)
  • /etc/profile is not a part of the regular list of startup files run for Zsh, but is sourced from /etc/zsh/zprofile in the zsh package. Users should take note that /etc/profile sets the $PATH variable which will overwrite any $PATH variable set in $ZDOTDIR/.zshenv. To prevent this, please set the $PATH variable in $ZDOTDIR/.zprofile
Warning: It is not recommended to replace the default one line in /etc/zsh/zprofile with something other, it'll break the integrality 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

Normally, the path should be set in ~/.zshenv, but Arch Linux sources /etc/profile after sourcing ~/.zshenv.

To prevent your $PATH being overwritten, set it in ~/.zprofile.

~/.zprofile
typeset -U path
path=(~/bin /other/things/in/path $path[@])

See also A User's Guide to the Z-Shell and the note in #Startup/Shutdown files.

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 need to prevent ssh from hashing hosts names in ~/.ssh/known_hosts.

Warning: This makes the computer vulnerable to "Island-hopping" attacks. In that intention, comment the following line or set the value to no:
/etc/ssh/ssh_config
#HashKnownHosts yes

And move ~/.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 hashed-hosts.

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

Autostart X at login

See Xinitrc#Autostart X at login.

The "command not found" hook

See Pkgfile#Command not found.

The ttyctl command

[1] describes the 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:

~/.zshrc
ttyctl -f

Key bindings

Zsh does not use readline, instead it uses its own and more powerful zle. It does not read /etc/inputrc or ~/.inputrc. 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.

See also zshwiki: bindkeys.

Bind key to ncurses application

Bind a ncurses application to a keystoke, 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

Alternate way to bind ncurses application

This method 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      > /dev/null
  zle       reset-prompt
  echo
  ls
  echo
}

cdParentKey() {
  pushd .. > /dev/null
  zle      reset-prompt
  echo
  ls
  echo
}

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

History search

Add these lines to .zshrc

~/.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

Doing this, only past commands matching the current line up to the current cursor position will be shown.

Prompts

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 .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

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 PROMPT= with prompt escapes.

See Prompt Expansion for a list of prompt variables and conditional substrings, or take a look at the zshmisc(1) manpage.

Colors

Zsh sets colors differently than Bash. Add autoload -Uz colors && colors before PROMPT= in .zshrc to use them. Usually you will want to put these inside %{ [...] %} so the cursor does not move.

Command Description
$fg[color] will set the text color (red, green, blue, etc. - defaults to whatever format set prior to text)
%F{color} [...] %f effectively the same as the previous, but with less typing. Can also prefix F with a number instead.
$fg_no_bold[color] will set text to non-bold and set the text color
$fg_bold[color] will set the text to bold and set the text color
$reset_color will reset the text color to the default color. Does not reset bold. use %b to reset bold. Saves typing if it's just %f though.
%K{color} [...] %k will set the background color. Same color as non-bold text color. Prefixing with any single-digit number makes the bg black.
%S [...] %s Standout mode, switches the text and background colors. Useful for Powerline-like prompts, especially if you switch between light/dark backgrounds.
Possible color values
black or 0 red or 1
green or 2 yellow or 3
blue or 4 magenta or 5
cyan or 6 white or 7
Note: Bold text does not necessarily use the same colors as normal text. For example, $fg['yellow'] looks brown or a very dark yellow, while $fg_bold['yellow'] looks like bright or regular yellow.
Example

This is an example of a two-sided prompt:

PROMPT="%{$fg[red]%}%n%{$reset_color%}@%{$fg[blue]%}%m %{$fg_no_bold[yellow]%}%1~ %{$reset_color%}%# "
RPROMPT="[%{$fg_no_bold[yellow]%}%?%{$reset_color%}]"

And here's how it will be displayed:

username@host ~ %                                                         [0]

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
DIRSTACKFILE="$HOME/.cache/zsh/dirs"
if [[ -f $DIRSTACKFILE ]] && [[ $#dirstack -eq 0 ]]; then
  dirstack=( ${(f)"$(< $DIRSTACKFILE)"} )
  [[ -d $dirstack[1] ]] && cd $dirstack[1]
fi
chpwd() {
  print -l $PWD ${(u)dirstack} >$DIRSTACKFILE
}

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. To use cdr add the following lines to shell configuration:

.zshrc
autoload -Uz chpwd_recent_dirs cdr add-zsh-hook
add-zsh-hook chpwd chpwd_recent_dirs

Recent directories list by default is stored in ${ZDOTDIR:-$HOME}/.chpwd-recent-dirs, to change it use zstyle:

zstyle ':chpwd:*' recent-dirs-file "${XDG_CACHE_HOME:-$HOME/.cache}/zsh/chpwd-recent-dirs"

Every time you change directory interactively, no matter which command you use, the directory to which you change will be remembered in most-recent-first order.

To print the list of recent directories use:

$ cdr -l

Use cdr <NUM> to go back to a visited folder. Completion for the argument to cdr is available if compinit has been run; menu selection is recommended.

Help command

Unlike bash, zsh does not enable a built in help command. To use help in zsh, add following to your zshrc:

autoload -Uz run-help
autoload -Uz run-help-git
autoload -Uz run-help-svn
autoload -Uz run-help-svk
unalias run-help
alias help=run-help

Fish-like syntax highlighting

Fish provides a very powerful shell syntax highlighting. To use this in zsh, you can install zsh-syntax-highlighting from offical repository and add following to your zshrc:

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

Sample .zshrc files

See Dotfiles#Repositories for more.

Configuration Frameworks

Tango-edit-clear.pngThis article or section needs language, wiki syntax or style improvements.Tango-edit-clear.png

Reason: List needs to be changed to Template:App. (Discuss in Talk:Zsh#)
  • Antigen (available as antigen-gitAUR) - A plugin manager for zsh, inspired by oh-my-zsh and vundle.
  • oh-my-zsh is a popular, community-driven framework for managing your Zsh configuration. It comes bundled with a ton of helpful functions, helpers, plugins, themes.
  • Prezto - Instantly Awesome Zsh (available as prezto-gitAUR) is 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.

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 exectuables included, one would run:

$ rehash

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

~/.zshrc
zstyle ':completion:*' rehash true
Note: This hack has been found in a PR for Oh My Zsh [2]

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 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