# Zsh (简体中文)

Zsh是一款强大的虚拟终端，既是一个系统的虚拟终端，也可以作为一个脚本语言的交互解析器。它在兼容Bash的同时 (默认不兼容，除非设置成 "emulate sh")，有如下优点：

- 更快
- 优化了的自动补全
- 优化的模式识别
- Improved array handling
- 全面可定制

Zsh的常见问题解答有更详细的解释。

## 安装

为免重复安装，可以先看看目前所使用的终端是什么：

    $ echo $SHELL

zsh在官方维护仓库中，可以和其他类似软件一样安装 .

### 初始化配置文件

先运行一下，看看软件是否已经正确安装：

    $ zsh

将会看到 zsh-newuser-install,新手向导将可以帮你完成一些最基本的配置。若想跳过，按`q`键退出.

### 把Zsh变成默认终端

若`/etc/shells`文件中已列有zsh，则可以使用 `chsh` 来改变默认的终端——此命令不需要以根账户使用，但使用过程中需要使用根账户密码。 如果是从官方维护的仓库中安装Zsh，则`/etc/shells`已列有zsh。

让目前使用的用户改变默认虚拟终端:

    $ chsh -s $(which zsh)

注意: 修改完后要重新登录才能见效

重新登录之后，会在终端中看到Zsh的提示符，和Bash是不一样的。如果还有疑惑，可输入下面命令看看默认终端是那个:

    $ echo $SHELL

小贴士: 如果你要替换 bash，你也许需要移动 `~/.bashrc` 中的一些代码到 `~/.zshrc` (例如：命令提示符和别名)，以及移动 `~/.bash_profile` 中的一些代码到 `~/.zprofile` (例如 启动 X Window System 的代码)。

## 配置文件介绍

用户登录时，Zsh会按顺序读取以下文件:

`~/.zshenv`
  This file should contain commands to set the 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.
`/etc/profile`
  This file is sourced by all Bourne-compatible shells upon login: it sets up an environment upon login and application-specific (`/etc/profile.d/*.sh`) settings.
`~/.zprofile`
  This file is generally used for automatic execution of user's scripts.
`~/.zshrc`
  This is Zsh's main configuration file.
`~/.zlogin`
  This file is generally used for automatic execution of user's scripts.

注销时，Zsh会读取`~/.zlogout`

Note:

- 在Arch源中的zsh所使用的paths和Zsh的mam pages中默认的不同.
- `$ZDOTDIR`的默认值是`$HOME`
- `/etc/profile`并不是Zsh的配置文件，但`/etc/zsh/zprofile`默认会读取`/etc/profile`。由于在`/etc/profile`中设定了`$PATH`并且会覆盖掉在`~/.zshenv`的`$PATH`。可修改`/etc/zsh/profile`，或者在`~/.zshrc`中重新设`$PATH`

## 用于定制的配置文件 ~/.zshrc

尽管 Zsh 是开箱即可使用的，但是它基本上不会设置成你想要使用的样子。但是由于 Zsh 中有大量的可定制的选项，配置Zsh也许是一个使人气馁和花费时间的经历。

下面的是一个示例配置文件，它提供了一系列默认选项，同时也提供了许多配置Zsh的例子。为了使用这个配置文件，你可以将它保存成 `.zshrc`。你可以不需要登出再登入就可以使用下面的命令应用更改：

    $ source ~/.zshrc

### 简单的 .zshrc

下面是一个简单的`.zshrc`配置文件，足够用于起步：

    ~/.zshrc

    autoload -U compinit promptinit
    compinit
    promptinit

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

### 命令提示和补全

自动补全是Zsh的王牌功能，不可不好好利用。加入下列行到配置文件`.zshrc`中，开启此功能:

    ~/.zshrc

    autoload -U 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 ~/.ssh/known_hosts (Warning: be aware that this makes your 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 your ~/.ssh/known_hosts somewhere else so that ssh creates a new one with with un-hashed hostnames (warning: previously known hosts will thus be lost).

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

    ~/.zshrc

    zstyle ':completion:*' menu select

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

    ~/.zshrc

    setopt completealiases

### 快捷键绑定

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. By default, it tries to guess whether you want emacs or vi keys from the $EDITOR environment variable. If it is empty, it will default to emacs. You can change this with bindkey -v or bindkey -e.

To get some special keys working:

    ~/.zshrc

    bindkey "\e[1~" beginning-of-line # Home
    bindkey "\e[4~" end-of-line # End
    bindkey "\e[5~" beginning-of-history # PageUp
    bindkey "\e[6~" end-of-history # PageDown
    bindkey "\e[2~" quoted-insert # Ins
    bindkey "\e[3~" delete-char # Del
    bindkey "\e[5C" forward-word
    bindkey "\eOc" emacs-forward-word
    bindkey "\e[5D" backward-word
    bindkey "\eOd" emacs-backward-word
    bindkey "\e\e[C" forward-word
    bindkey "\e\e[D" backward-word
    bindkey "\e[Z" reverse-menu-complete # Shift+Tab
    # for rxvt
    bindkey "\e[7~" beginning-of-line # Home
    bindkey "\e[8~" end-of-line # End
    # for non RH/Debian xterm, can't hurt for RH/Debian xterm
    bindkey "\eOH" beginning-of-line
    bindkey "\eOF" end-of-line
    # for freebsd console
    bindkey "\e[H" beginning-of-line
    bindkey "\e[F" end-of-line

Alternatively, you can convert /etc/inputrc for Zsh:

    ~/.zshrc

    # bind special keys according to readline configuration
    eval "$(sed -n 's/^/bindkey /; s/: / /p' /etc/inputrc)"

Note: To get the proper sequences for certain key combinations, start `cat` or `read` without any parameters and press them; they should then be printed in the terminal. Both can be closed again via `Ctrl`+`C`.

### 历史类似操作查看

把下面的文字加入配置文件.zshrc中：

    ~/.zshrc

    bindkey "^[[A" history-search-backward
    bindkey "^[[B" history-search-forward

这可以使开头和目前已输入的部分相同的历史操作会被显示出来。

### 命令提示符

There is a quick and easy way to set up a colored prompt in Zsh. Make sure that prompt is set to autload in your `.zshrc`. This can be done by adding these lines to:

    ~/.zshrc

    autoload -U promptinit
    promptinit

You can now see available prompts by running the command:

    $ 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 "walters" prompt, you would enter:

    $ prompt walters

### 自定义命令提示符

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. To customize it, the following variables can be used:

#### 命令提示符变量

##### 常用

%n
  用户名
%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 (`#` for root and `%` for the rest)

##### 时间

%T
  系统时间(格式为HH:MM)
%*
  系统时间(格式为HH:MM:SS)
%D
  系统日期(格式为YY-MM-DD)

##### 路径

%d
  表示目前所在的工作路径。
%~
  表示目前所在的工作路径。若在你的家目录 $HOME 或其子目录下，则 $HOME 的部分会被替换为"~"。

For the options mentioned above: You can prefix an integer to show only certain parts of your working path. If you entered `%1d` and found yourself in `/usr/bin` it would show `bin`. This can also be done with negative integers: `%-1d` using the same directory as above would show `/`.

##### 格式化

%U [...] %u
  给某段话下划线的开始和结束标识
%B [...] %b
  给某段话加粗的开始和结束标识
%{ [...] %}
  让某段话不显示在屏幕上的开始和结束标识。这是有用的，比如用于颜色设置。

##### 配色

Zsh has a different approach to setting colors on the terminal than the one depicted here. First you write in your `.zshrc`:

    autoload -U colors && colors

Following commands would now produce the color escape sequence needed to set the requested color when the prompt is printed:

$fg[color]
  will set the textcolor(red,green,blue, etc)
$reset_color
  will reset the textcolor to white

It is useful to put these commands in `%{ [...] %`}.

#### 示例

To have a two-sided prompt you could write:

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

It would equal(without colors):

    username@host ~ %                                                         [0]

### 更进一步的配置 .zshrc

One could also find a great way to manage its Zsh configuration by using Oh-my-zsh created by Robby Russel which contains a lot of user contributed plugins and themes but most importantly a great community of more than 900 forks on github.

This is an example of a more advanced `.zshrc`.

    ~/.zshrc

    ###########################################################
    # Options for Zsh

    export HISTFILE=~/.zsh_history
    export HISTSIZE=50000
    export SAVEHIST=50000
    eval `dircolors -b`

    autoload -U compinit compinit
    setopt autopushd pushdminus pushdsilent pushdtohome
    setopt autocd
    setopt cdablevars
    setopt ignoreeof
    setopt interactivecomments
    setopt nobanghist
    setopt noclobber
    setopt HIST_REDUCE_BLANKS
    setopt HIST_IGNORE_SPACE
    setopt SH_WORD_SPLIT
    setopt nohup

    # PS1 and PS2
    export PS1="$(print '%{\e[1;34m%}%n%{\e[0m%}'):$(print '%{\e[0;34m%}%~%{\e[0m%}')$ "
    export PS2="$(print '%{\e[0;34m%}>%{\e[0m%}')"

    # Vars used later on by Zsh
    export EDITOR="nano"
    export BROWSER=links
    export XTERM="aterm +sb -geometry 80x29 -fg black -bg lightgoldenrodyellow -fn -xos4-terminus-medium-*-normal-*-14-*-*-*-*-*-iso8859-15"

    ##################################################################
    # Stuff to make my life easier

    # allow approximate
    zstyle ':completion:*' completer _complete _match _approximate
    zstyle ':completion:*:match:*' original only
    zstyle ':completion:*:approximate:*' max-errors 1 numeric

    # tab completion for PID :D
    zstyle ':completion:*:*:kill:*' menu yes select
    zstyle ':completion:*:kill:*' force-list always

    # cd not select parent dir
    zstyle ':completion:*:cd:*' ignore-parents parent pwd

    # useful for path editing — backward-delete-word, but with / as additional delimiter
    backward-delete-to-slash () {
      local WORDCHARS=${WORDCHARS//\//}
      zle .backward-delete-word
    }
    zle -N backward-delete-to-slash

    ##################################################################
    # Key bindings
    # http://mundy.yazzy.org/unix/zsh.php
    # http://www.zsh.org/mla/users/2000/msg00727.html

    typeset -g -A key
    bindkey '^?' backward-delete-char
    bindkey '^[[1~' beginning-of-line
    bindkey '^[[5~' up-line-or-history
    bindkey '^[[3~' delete-char
    bindkey '^[[4~' end-of-line
    bindkey '^[[6~' down-line-or-history
    bindkey '^[[A' up-line-or-search
    bindkey '^[[D' backward-char
    bindkey '^[[B' down-line-or-search
    bindkey '^[[C' forward-char
    bindkey '^[w' backward-delete-to-slash
    # completion in the middle of a line
    bindkey '^i' expand-or-complete-prefix

    ##################################################################
    # My aliases

    # Set up auto extension stuff
    alias -s html=$BROWSER
    alias -s org=$BROWSER
    alias -s php=$BROWSER
    alias -s com=$BROWSER
    alias -s net=$BROWSER
    alias -s png=feh
    alias -s jpg=feh
    alias -s gif=feg
    alias -s sxw=soffice
    alias -s doc=soffice
    alias -s gz='tar -xzvf'
    alias -s bz2='tar -xjvf'
    alias -s java=$EDITOR
    alias -s txt=$EDITOR
    alias -s PKGBUILD=$EDITOR

    # Normal aliases
    alias ls='ls --color=auto -F'
    alias lsd='ls -ld *(-/DN)'
    alias lsa='ls -ld .*'
    alias f='find |grep'
    alias c="clear"
    alias dir='ls -1'
    alias gvim='gvim -geom 82x35'
    alias ..='cd ..'
    alias nicotine='/home/paul/downloads/nicotine-1.0.8rc1/nicotine'
    alias ppp-on='sudo /usr/sbin/ppp-on'
    alias ppp-off='sudo /usr/sbin/ppp-off'
    alias firestarter='sudo su -c firestarter'
    alias mpg123='mpg123 -o oss'
    alias mpg321='mpg123 -o oss'
    alias vba='/home/paul/downloads/VisualBoyAdvance -f 4'
    alias hist="grep '$1' /home/paul/.zsh_history"
    alias irssi="irssi -c irc.freenode.net -n yyz"
    alias mem="free -m"
    alias msn="tmsnc -l hutchy@subdimension.com"

    # command L equivalent to command |less
    alias -g L='|less'

    # command S equivalent to command &> /dev/null &
    alias -g S='&> /dev/null &'

There are many more ways that you can customise Zsh, obviously far too many to list here, see the Zsh manual for more information.

### .zshrc文件实例

这是一些用户的`.zshrc`配置文件，如果你认为你的配置也很有特色，欢迎加进这个列表里：

- Oh-my-zsh Plugin and Theme system for Zsh is a must have to manage your zshrc file and to take advantage of a huge community of over 900 forks on github;
- Basic setup, with dynamic prompt and window title/hardinfo => http://github.com/MrElendig/dotfiles-alice/blob/master/.zshrc;
- An Arch package named 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 wnat to run poweroff, reboot or hibernate, support for GIT in prompt (done without vcsinfo), tab complation with menu, printing current executed command into window's title bar and 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 `/etc/zshrc`. This however is slightly different on ArchLinux, since it has been compiled with flags specifically to target `/etc/zsh/` instead.

So, for global configuration use `/etc/zsh/zshrc`, not `/etc/zshrc`. The same goes for `/etc/zsh/zshenv`, `/etc/zsh/zlogin` and `/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.

The only exception is zprofile, use `/etc/profile` instead.

### 自动开启应用

Zsh always executes `/etc/zsh/zshenv` and `$ZDOTDIR/.zshenv` so do not bloat these files.

If the shell is a login shell, commands are read from `/etc/profile` and then `$ZDOTDIR/.zprofile`. Then, if the shell is interactive, commands are read from `/etc/zsh/zshrc` and then `$ZDOTDIR/.zshrc`. Finally, if the shell is a login shell, `/etc/zsh/zlogin` and `$ZDOTDIR/.zlogin` are read.

## 卸载

若想卸载，先要改变默认虚拟终端，比如，先恢复成Bash。

按照Zsh#Making Zsh your default shell的方法改变默认虚拟终端，把zsh替换为bash即可恢复默认虚拟终端为bash。

之后，就可以安全地卸载Zsh软件包了。

警告: 若上述步骤失败，将引发众多问题，所以请务必严格执行之。

若没按照上面所述去做，还可以用另外的方式改变默认虚拟终端，方法是以根用户身份修改 /etc/passwd 例如:

把:

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

改为:

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

## konsole中配置zsh

待写

## 更多信息可见

- Zsh Introduction
- Users Guide
- Zsh Docs (you can choose a different format for the doc in http://zsh.sourceforge.net/Doc/)
- Zsh FAQ
- Zsh Wiki
- Zsh-lovers
- Bash2Zsh Reference Card
- Oh My Zshell by Robby Russell
- Gentoo zsh wiki article
- Setting up the zsh prompt

- IRC channel: #zsh at irc.freenode.org

Category:

- Command shells (简体中文)