Zsh (日本語)
Zsh は対話式シェルとしてもスクリプト言語のインタプリタとしても使えるパワフルなシェルです。Bash と互換性がありながら (デフォルトではありません、"emulate sh" を実行した時だけです)、Zsh には多くの利点があります:
- 高速
- 高度なタブ補完
- 高度なグロブ
- 高度な行列処理
- 完全にカスタマイズ可能
Zsh FAQ には他にも Zsh をあなたのシェルとして使うべき 理由 が列挙されています。
Contents |
インストール
インストールをする前に現在使っているシェルが何なのか知っておくとよいでしょう:
$ echo $SHELL
公式リポジトリにある zsh パッケージをインストールしてください。
初期設定
ターミナルで次のコマンドを実行して Zsh が正しくインストールされたか確認してください:
$ zsh
基本的な設定を説明する zsh-newuser-install が表示されるはずです。これをスキップしたい場合、q を押して下さい。
Zsh をデフォルトのシェルにする
シェルが /etc/shells に記載されていれば、chsh コマンドを使って root 権限なしでデフォルトシェルを変更することができます。公式リポジトリから Zsh をインストールしたのなら、既に /etc/shells にエントリが作られているはずです。
現在使っているユーザーのデフォルトシェルを変更するには:
$ chsh -s $(which zsh)
最ログイン後、Bash とは見た目が異なる Zsh のプロンプトが表示されていることに気づくでしょう。また、次のコマンドを実行することで Zsh が現在のシェルになっていることを確認できます:
$ echo $SHELL
設定ファイル
ログイン時、Zsh は以下のファイルをこの順番で読み込みます:
~/.zshenv- このファイルにはコマンドの検索パスを設定するコマンドや、重要な環境変数を含めます; 出力をするコマンドや tty に基づいているコマンドを含めてはいけません。
/etc/profile- このファイルはログイン時に Bourne 互換シェルによって読み込まれます: ログイン時やアプリケーション固有の設定
/etc/profile.d/*.sh) を設定します。 ~/.zprofile- このファイルは一般的にユーザーのスクリプトを自動で実行するために使われます。
~/.zshrc- これは Zsh のメインの設定ファイルです。
~/.zlogin- このファイルは一般的にユーザーのスクリプトを自動で実行するために使われます。
ログアウト時には ~/.zlogout が読み込まれます。このファイルはユーザーのスクリプトを自動で実行するために使われます。
$PATH 変数を設定すると ~/.zshenv に設定した $PATH 変数を全て上書きしてしまうので注意してください。これを防ぐには、/etc/zsh/zprofile をあなたの作ったファイルに置き換えるか、~/.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
$PATH の設定
zsh でユーザーごとにシステムパスを設定する方法についての情報はここにあります: http://zsh.sourceforge.net/Guide/zshguide02.html#l24
以下を ~/.zshenv に追加してください:
~/.zshenv
typeset -U path path=(~/bin /other/things/in/path $path)
コマンド補完
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.
矢印キーのインターフェイスを使って自動補完するには、以下を追加して下さい:
~/.zshrc
zstyle ':completion:*' menu select
- メニューを有効にするには、タブを二度押して下さい。
エイリアスでコマンドラインの自動補完を切り替えるには、以下を追加して下さい:
~/.zshrc
setopt completealiases
"command not found" フック
pkgfile パッケージには、不明なコマンドを入力したときに自動で公式リポジトリを検索する "command not found" フックが含まれています。例えば以下のように表示されます:
$ abiword
abiword may be found in the following packages: extra/abiword 2.8.6-7 usr/bin/abiword
以下を使って pkgfile をロードしてください:
~/.zshrc
source /usr/share/doc/pkgfile/command-not-found.zsh
他にも AUR のパッケージ command-not-found によって提供されている "command not found" フックもあり、以下のように出力を生成します:
$ 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 ]
これを使うには、以下を zshrc に追加して下さい:
[ -r /etc/profile.d/cnf.sh ] && . /etc/profile.d/cnf.sh
履歴に同じ行が重複するのを避ける
履歴の重複する行を無視するととても便利です。これをするには、以下を追加して下さい:
~/.zshrc
setopt HIST_IGNORE_DUPS
キーバインド
Zsh は readline を使っていません、代わりに自身のパワフルな zle を使っています。zle は /etc/inputrc や ~/.inputrc を読みません。
zle には emacs モードと vi モードがあります。デフォルトでは、$EDITOR 環境変数から emacs と vi どちらのキーをあなたが使いたいのか考えます。この変数が空の場合、デフォルトは emacs モードです。 bindkey -v や bindkey -e でモードを変更することが可能です。
特殊なキーを動作させるには:
~/.zshrc
# create a zkbd compatible hash;
# to add other keys to this hash, see: man 5 terminfo
typeset -A key
key[Home]=${terminfo[khome]}
key[End]=${terminfo[kend]}
key[Insert]=${terminfo[kich1]}
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]}
# 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[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
# active. Only then are the values from $terminfo valid.
if (( ${+terminfo[smkx]} )) && (( ${+terminfo[rmkx]} )); then
function zle-line-init () {
printf '%s' "${terminfo[smkx]}"
}
function zle-line-finish () {
printf '%s' "${terminfo[rmkx]}"
}
zle -N zle-line-init
zle -N zle-line-finish
fi
terminfo を使わない方法
autoload zkbd を実行してから zkbd を実行して下さい。キーを押せない場合は (例: F11 はウィンドウを最大化します)、スペースを押してスキップして下さい。zkbd が完了した後、以下を ~/.zshrc に追加して下さい:
~/.zshrc
autoload zkbd
source ~/.zkbd/$TERM-:0.0 # may be different - check where zkbd saved yours
[[ -n ${key[Backspace]} ]] && bindkey "${key[Backspace]}" backward-delete-char
[[ -n ${key[Insert]} ]] && bindkey "${key[Insert]}" overwrite-mode
[[ -n ${key[Home]} ]] && bindkey "${key[Home]}" beginning-of-line
[[ -n ${key[PageUp]} ]] && bindkey "${key[PageUp]}" up-line-or-history
[[ -n ${key[Delete]} ]] && bindkey "${key[Delete]}" delete-char
[[ -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
ncurses アプリケーションのキーバインド
ncurses アプリケーションをキーストロークにバインドすることが可能ですが、対話はできません。BUFFER 変数を使って動作させて下さい。以下の例は Alt+\ で ncmpcpp を開きます:
~/.zshrc
ncmpcppShow() { BUFFER="ncmpcpp"; zle accept-line; }
zle -N ncmpcppShow
bindkey '^[\' ncmpcppShow
履歴検索
You can add these lines to your .zshrc
~/.zshrc
[[ -n "${key[PageUp]}" ]] && bindkey "${key[PageUp]}" history-beginning-search-backward
[[ -n "${key[PageDown]}" ]] && bindkey "${key[PageDown]}" history-beginning-search-forward
Doing this, only past commands beginning with the current input would have been shown.
プロンプト
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 .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
To preview all available themes you could use this command:
$ prompt -p
プロンプトのカスタマイズ
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 PROMPT= with the following variables:
プロンプト変数
一般
- %n
- ユーザー名
- %m
- コンピュータのホスト名 (ドットの前の部分まで)
- %M
- コンピュータのホスト名
- %l
- 現在の tty
- %?
- 最後に実行したアプリケーションのリターンコード
- %#
- ユーザー特権によるプロンプト (root なら
#その他なら%)
時間
- %T
- システム時刻 (HH:MM)
- %*
- システム時刻 (HH:MM:SS)
- %D
- システム時間 (YY-MM-DD)
ディレクトリ
- %~
- カレントディレクトリ。
$HOMEの場合、~に置き換えられます。 - %d
- カレントディレクトリ。
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
- 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.
カラー
Zsh has a different approach to setting colors on the terminal than the one depicted here. First you write before PROMPT= 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 text color (red, green, blue, etc. - defaults to bold)
- $fg_no_bold[color]
- will set the non-bold text color
- $fg_bold[color]
- will set the bold text color
- $reset_color
- will reset the text color to the default color
It is useful to put these color commands inside %{ [...] %} , so the shell knows there is no output from these sequences and the cursor hasn't moved.
- Possible color values
| black | red |
| green | yellow |
| blue | magenta |
| cyan | white |
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.
サンプル
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%}%#"
RPROMPT="[%{$fg_no_bold[yellow]%}%?%{$reset_color%}]"
It would equal(without colors):
username@host ~ % [0]
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 you 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 autopushd pushdsilent pushdtohome
## Remove duplicate entries
setopt pushdignoredups
## This reverts the +/- operators.
setopt pushdminus
Now you can use
dirs -v
to print the dirstack. Use 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.
サンプル .zshrc ファイル
Here is a list of .zshrc files. Feel free to add your own:
- Prezto - Instantly Awesome Zsh (AUR package: 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.
- 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 completion 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.
See also the STARTUP/SHUTDOWN FILES section of man zsh.
アンインストール
Zsh があなたに合わないと感じて Bash に戻りたいときは、Zsh パッケージを削除する前に必ず、まずデフォルトシェルを変更して下さい。
ターミナルで次のコマンドを root で実行して下さい:
# chsh -s /bin/bash user
Zsh を使っている全てのユーザーで実行して下さい。
これで安全に Zsh パッケージを削除することができます。
以上を行わなかった場合、root で /etc/passwd を編集することで Bash にデフォルトシェルを戻すことができます。
例:
編集前:
username:x:1000:1000:Full Name,,,:/home/username:/bin/zsh
編集後:
username:x:1000:1000:Full Name,,,:/home/username:/bin/bash
参照
- 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 Linux Documentation -- Zsh configuration and installation guide
- Setting up the Zsh prompt
- IRC チャンネル: #zsh at irc.freenode.org