Zsh

提供: ArchWiki
2021年10月23日 (土) 14:47時点におけるKusanaginoturugi (トーク | 投稿記録)による版 (→‎Autostart X at login: 翻訳)
ナビゲーションに移動 検索に移動

Zsh は対話式シェルとしてもスクリプト言語のインタプリタとしても使えるパワフルなシェルです。POSIX sh と互換性がありながら (デフォルトではありません、emulate sh を実行した時だけです)、タブ補完の改善や グロビングなどの利点があります。

Zsh FAQ には他にも Zsh をあなたのシェルとして使うべき理由が列挙されています。

目次

インストール

インストールをする前に現在使っているシェルが何なのか知っておくとよいでしょう:

$ echo $SHELL

公式リポジトリにある zsh パッケージをインストールしてください。追加の補完定義を使いたい場合は、zsh-completions パッケージもインストールします。

初期設定

ターミナルで次のコマンドを実行して Zsh が正しくインストールされたか確認してください:

$ zsh

基本的な設定を説明する zsh-newuser-install が表示されるはずです。これをスキップしたい場合、q を押して下さい。表示されない場合は、次のコマンドで手動で呼び出すことができます:

$ autoload -Uz zsh-newuser-install
$ zsh-newuser-install -f
ノート: 仮想端末のサイズが少なくとも 72×15 であることを確認してください。そうでないと zsh-newuser-install は実行されません。

Zsh をデフォルトのシェルにする

シェルが /etc/shells に記載されていれば、chsh コマンドを使って root 権限なしでデフォルトシェルを変更することができます。公式リポジトリから Zsh をインストールしたのなら、既に /etc/shells にエントリが作られているはずです。

現在使っているユーザーのデフォルトシェルを変更するには:

$ chsh -s $(which zsh)
ノート: Zsh をデフォルトシェルとして起動するには、一度ログアウトしてからログインしなおす必要があります。

再ログイン後、Bash とは見た目が異なる Zsh のプロンプトが表示されていることに気づくでしょう。また、次のコマンドを実行することで Zsh が現在のシェルになっていることを確認できます:

$ echo $SHELL
ヒント: bash を置き換える場合、~/.bashrc から ~/.zshrc に (例: プロンプトとエイリアス) また ~/.bash_profile から ~/.zprofile に (例: X Window System を起動するコード) にコードを移動するとよいでしょう。

スタートアップ/シャットダウン ファイル

ヒント:
  • インタラクティブシェルとログインシェルの説明、およびスタートアップファイルに何を入れるかについては、A User's Guide to the Z-Shell を参照してください。
  • Zsh 構成ファイルには 標準パスの実装 を検討できます。
ノート:
  • $ZDOTDIR が設定されていない場合は、代わりに $HOME が使用されます。
  • オプション RCS がいずれかのファイルで設定されていない場合、そのファイルの後に構成ファイルは読み取りません。
  • オプション GLOBAL_RCS がいずれかのファイルで設定されていない場合、そのファイルの後にグローバル構成ファイル(/etc/zsh/*)は読み取りません。

ログイン時、Zsh は以下のファイルをこの順番で読み込みます:

/etc/zsh/zshenv
このファイルにはグローバルなコマンド検索パスやシステム共通の環境変数を設定するコマンドを記述します。出力を発生させるコマンドや tty に基づいているコマンドを含めてはいけません。
~/.zshenv
このファイルにはコマンドの検索パスを設定するコマンドや、重要な環境変数を含めます; 出力をするコマンドや tty に基づいているコマンドを含めてはいけません。
/etc/zsh/zprofile
グローバルな設定ファイルであり、ログイン時に読み込まれます。ログイン時に毎回実行するコマンドを記述するのに使われます。Arch Linux では、初めから /etc/profile を source する一行が入っています。詳しくはを参照。
/etc/profile
このファイルはログイン時に Bourne 互換シェルによって読み込まれます: ログイン時やアプリケーション固有の設定 /etc/profile.d/*.sh) を設定します。
~/.zprofile
このファイルは一般的にユーザーのスクリプトを自動で実行するために使われます。
/etc/zsh/zshrc
グローバルな設定ファイルであり、インタラクティブシェルとして起動した場合に読み込まれます。
~/.zshrc
これは Zsh のメインの設定ファイルです。
/etc/zsh/zlogin
グローバルな設定ファイルであり、ログインシェルとして起動した場合に、初期化の最後に読み込まれます。
~/.zlogin
/etc/zsh/zlogin と同じ設定ファイルですが、ユーザーごとの設定を記述するところが違います。
/etc/zsh/zlogout
グローバルな設定ファイルであり、ログインシェルが終了するときに読み込まれます。
~/.zlogout
/etc/zsh/zlogout と同じ設定ファイルですが、ユーザーごとの設定を記述するところが違います。
ノート:
  • Arch の zsh パッケージで使われているパスは man ページで使われているデフォルトのパスとは異なっています。
  • $ZDOTDIR のデフォルトは $HOME です。
  • /etc/profile は Zsh のスタートアップファイルの標準リストに含まれていませんが、zsh パッケージに入っている /etc/zsh/zprofile から読み込まれます。/etc/profile$PATH 変数を設定すると ~/.zshenv に設定した $PATH 変数を全て上書きしてしまうので注意してください。これを防ぐには、/etc/zsh/zprofile をあなたの作ったファイルに置き換えるか、~/.zshrc から $PATH 変数を設定してください。

全ユーザー共通の設定ファイル

場合によっては Zsh ユーザー全てに設定を適用させたいときもあると思われます。zsh(1) によれば /etc/zshrc などグローバルな設定ファイルはいくつか存在します。ただし、これは Arch では少し事情が異なっており、代わりに /etc/zsh/ を使うようにコンパイルされています [1]

従って、ユーザー共通の設定をしたいときは /etc/zshrc ではなく /etc/zsh/zshrc を使って下さい。これは /etc/zsh/zshenv, /etc/zsh/zlogin, /etc/zsh/zlogout でも同じです。これらのファイルはデフォルトではインストールされないので、必要なときに作成してください。

唯一の例外は zprofile で、これは /etc/profile を使います。

~/.zshrc の設定

Zsh は何も設定しなくても使うことができますが、あなたが使いたい機能はほとんど設定されていないでしょう。ただし Zsh で利用できるカスタム化の道は険しく、Zsh の設定は困難をきわめ多くの時間を浪費するかもしれません。

シンプルな .zshrc

下にはサンプルの設定ファイルが含まれており、Zsh のカスタマイズの方法の例だけでなくデフォルトオプションのセットも提供しています。この設定を使うには .zshrc という名前でファイルを保存してください。ログインしなおさなくても次を実行することで変更を適用できます:

$ source ~/.zshrc

以下はシンプルな .zshrc です、基点としてはピッタリでしょう:

~/.zshrc
autoload -U compinit promptinit
compinit
promptinit

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

$PATH の設定

通常、PATH は ~/.zshenv で設定すべきですが、Arch Linux は ~/.zshenv を読み込んだ後に /etc/profile を読み込みます (全体の流れは設定ファイルを見てください)。

$PATH の上書きを防ぐために、~/.zprofile で設定するようにしてください:

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

詳しくは Z-Shell のユーザーガイド を参照してください。

コマンド補完

Zsh の一番魅力的な機能はおそらく先進的な自動補完機能でしょう。少なくとも、.zshrc で自動補完を有効にしたいと思うはずです。自動補完を有効にするには、以下を追加してください:

~/.zshrc
autoload -U compinit
compinit

この設定は ssh/scp/sftp のホスト名の補完も含んでいますが、この機能を動かすには ~/.ssh/known_hosts で ssh がホスト名をハッシュ化しないようにする必要があります。

警告: ハッシュ化を解除すると "Island-hopping" 攻撃 に無防備になります。そのことを前もって知った上で、次の行をコメントアウトするか値を no に設定してください:
/etc/ssh/ssh_config
#HashKnownHosts yes

これで ~/.ssh/known_hosts をどこか他のところに移動すれば ssh はハッシュ化されてないホスト名を使って新しいファイルを作成します (以前のホストは消失します)。詳細については、hashed-hosts に関する SSH の readme を見て下さい。

矢印キーのインターフェイスを使って自動補完するには、以下を追加して下さい:

~/.zshrc
zstyle ':completion:*' menu select
メニューを有効にするには、タブを二度押して下さい。

エイリアスでコマンドラインの自動補完を切り替えるには、以下を追加して下さい:

~/.zshrc
setopt completealiases

キーバインド

Zsh は readline を使っていません、代わりに自身のパワフルな zle を使っています。zle は /etc/inputrc~/.inputrc を読みません。 zle には emacs モードと vi モードがあります。デフォルトでは、$EDITOR 環境変数から emacs と vi どちらのキーをあなたが使いたいのか考えます。この変数が空の場合、デフォルトは emacs モードです。 bindkey -vbindkey -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
ノート: 特定のキーの組み合わせに対して適切なシーケンスを取得するには、 cat を起動するか、パラメーターなしで read を押します。 その後、端末に印刷する必要があります。 Ctrl+c を使用して両方を再び閉じることができます。

履歴検索

key 配列を設定し、ZLEがアプリケーションモードになっている事を確認して、以下の手順を使用してください。#キーバインド を参照してください。

履歴検索を有効にするには、以下の行を .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

これにより、up または down キーを押すと、現在の行から現在のカーソル位置までに一致する過去のコマンドのみが表示されます。

Shift, Alt, Ctrl and Meta 修飾キー

xterm 互換端末は user_caps(5) からの拡張キー定義を使うことができます。 ShiftAltCtrl、 および Meta と、 UpDownLeftRightPageUpPageDownHomeEnd、 または Del を組み合わせたものです。修飾キーとキーの組み合わせに推奨される名前の一覧については、 zkbd ソース を参照してください。

たとえば、 Ctrl+Left を前の単語の先頭に移動し、 Ctrl+Right を次の単語の先頭に移動するには、次のように指定します:

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

プロンプト

Zsh は、プロンプトテーマを使用するか、テーマに不満がある (またはその有用性を拡張したい) ユーザーのために、カスタムプロンプトを構築するオプションを提供しています。

プロンプトテーマ

プロンプトテーマは、Zshで色付きのプロンプトを設定するためのすばやく簡単な方法です。それらの詳細については、zshcontrib(1) § PROMPT THEMES を参照してください。

テーマを使用するには、プロンプトテーマシステムが、.zshrc に自動でロードされるよう設定されていることを確認してください。自動ロードを行うには、以下の行を追加します。

~/.zshrc
autoload -Uz promptinit
promptinit

次のコマンドを実行することで利用可能なプロンプトを見ることができます:

$ prompt -l

例えば、walters プロンプトを使うには、次のように入力します:

$ prompt walters

全ての利用可能なテーマをプレビューするには次のコマンドを使って下さい:

$ prompt -p
プロンプトテーマの手動インストール

外部の設定管理ツールを使わずに、テーマを手動でインストールすることもできます。ローカルインストールの場合、最初にフォルダを使用し、それを fpath 配列に通過します。例:

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

次に、このフォルダにテーマファイルのシンボリックリンクを作成します:

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

代わりに、テーマをグローバルにインストールする場合は、次のようにします:

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

これで、次のコマンドを使ってアクティブ化できるはずです:

$ prompt mytheme

すべてが機能する場合は、.zshrc をそれに応じて編集することができます。

ファイルの無いプロンプトテーマを追加する

プロンプトテーマを独自のファイルから追加するだけでなく、次のように別のファイル (.zshrc のように)からテーマを追加することもできます。 例えば:

~/.zshrc
# Load promptinit
autoload -Uz promptinit && promptinit

# Define the theme
prompt_mytheme_setup() {
  PS1="%~%# "
}

# Add the theme to promptsys
prompt_themes+=( mytheme )

# Load the theme
prompt mytheme

プロンプトのカスタマイズ

上述のプロンプトに満足がいかない(もしくはプロンプトを拡張したい)場合、Zsh にはカスタムプロンプトを作る機能が備わっています。全てのシェルに共通な左側だけのプロンプトに加え、Zsh は左右両側を使うプロンプトをサポートしています。PROMPT= と以下の変数を使うことでプロンプトをカスタマイズできます:

プロンプト変数
コマンド 説明 コメント
一般
%n ユーザー名
%m コンピュータのホスト名 (ドットの前の部分まで)
%M コンピュータのホスト名
%l 現在の tty
%? 最後に実行したアプリケーションのリターンコード
%# ユーザー特権によるプロンプト (root なら # その他なら %)
時間
%T システム時刻 (HH:MM)
%* システム時刻 (HH:MM:SS)
%D システム日付 (YY-MM-DD)
ディレクトリ
%d カレントディレクトリ。 数字を前に付けることでパスの一部だけを表示することが可能です。例えば %1d と入力した場合、/usr/bin にいるときは bin と表示されます。負の値も使えます: %-1d は上の例だと / と表示されます。
%~ カレントディレクトリ。$HOME やそのサブディレクトリにいる場合、$HOME の部分は ~ に置き換えられます。
整形
%U [...] %u 下線表示の始まりと終わり
%B [...] %b 太字表示の始まりと終わり
%{ [...] %} 表示されない領域。色の設定をするときに使います。このタグによって Zsh はタグの中にあるものを全て無視します。使用しないとプロンプトの縁やインデントに妙な影響が出ることがあります。
カラー
$fg[color] 文字色を設定します (red, green, blue など - 太字デフォルト)。 Zsh は Bash とは違ったふうに色を設定します。色を使うには .zshrcPROMPT= の前に autoload -U colors && colors を追加してください。通常、カーソルが動かないように色の設定は %{ [...] %} の中に記述します。
$fg_no_bold[color] 太字でない文字色を設定します。
$fg_bold[color] 太字の文字色を設定します。
$reset_color 文字色をデフォルトの色に戻します。
利用できるカラー
black または 0 red または 1
green または 2 yellow または 3
blue または 4 magenta または 5
cyan または 6 white または 7
ノート: 太字の文字色は通常の文字色と必ずしも同じ色になるわけではありません。例えば、$fg['yellow'] は褐色や濃黄のようになりますが、$fg_bold['yellow'] はやや明るい普通の黄色のようになります。
サンプル

以下のようにすることで左右両側にプロンプトを表示できます:

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

次のようになります (色は省略):

username@host ~ %                                                         [0]

サンプル .zshrc ファイル

以下は .zshrc ファイルのリストです。自由に自分のファイルを追加してください:

ヒントとテクニック

ログイン時に X を自動起動

xinitrc#ログイン時に X を自動起動を参照してください。

Restore terminal settings after a program exits abnormally

Many programs change the terminal state, and often do not restore terminal settings on exiting abnormally (e.g. when crashing or encountering SIGINT).

This can typically be solved by executing reset(1):

$ reset

The following sections describe ways to avoid the need to manually reset the terminal.

The ttyctl command

The ttyctl command can be used to "freeze/unfreeze" the terminal. To freeze the interactive shell on launch, use the following:

~/.zshrc
ttyctl -f

Resetting the terminal with escape sequences

Alternate linedrawing character set can screw up the terminal in a way which ttyctl cannot prevent.

A simple solution is to output the escape sequences that reset the terminal from the precmd hook function, so that they are executed every time before the prompt is drawn. For example, using the escape sequence \e[0m\e(B\e)0\017\e[?5l\e7\e[0;0r\e8:

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

function reset_broken_terminal () {
	printf '%b' '\e[0m\e(B\e)0\017\e[?5l\e7\e[0;0r\e8'
}

add-zsh-hook -Uz precmd reset_broken_terminal

To test if it works, run:

$ print '\e(0\e)B'

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.

ノート: 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) § REMEMBERING RECENT DIRECTORIES for setup instructions.

zoxide

zoxide is a smarter cd command that lets you navigate anywhere in just a few keystrokes. It remembers your frequently used directories and uses a scoring mechanism to guess where you want to go.

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
(( ${+aliases[run-help]} )) && unalias run-help
alias help=run-help

Assistant functions have to be enabled separately:

autoload -Uz run-help-git run-help-ip run-help-openssl run-help-p4 run-help-sudo run-help-svk 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.[2] 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
警告: 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
TRAPUSR1() { rehash }

The function trap above can be replaced with a list trap trap 'rehash' USR1. See zshmisc(1) § Trap Functions for differences between types of traps.

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
  print
  ls
  zle       reset-prompt
}

cdParentKey() {
  pushd ..
  zle      reset-prompt
  print
  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) § Hook Functions for a list of available hook functions and their descriptions.

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

ヒント:
  • 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.
ノート:
  • 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" == (Eterm*|alacritty*|aterm*|gnome*|konsole*|kterm*|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

pacman -F "command not found" handler

pacman includes functionality to search for packages containing a file. The following command-not-found handler will use pacman directly to search for matching packages when an unknown command is executed.

~/.zshrc
...
function command_not_found_handler {
    local purple='\e[1;35m' bright='\e[0;1m' green='\e[1;32m' reset='\e[0m'
    printf 'zsh: command not found: %s\n' "$1"
    local entries=(
        ${(f)"$(/usr/bin/pacman -F --machinereadable -- "/usr/bin/$1")"}
    )
    if (( ${#entries[@]} ))
    then
        printf "${bright}$1${reset} may be found in the following packages:\n"
        local pkg
        for entry in "${entries[@]}"
        do
            # (repo package version file)
            local fields=(
                ${(0)entry}
            )
            if [[ "$pkg" != "${fields[2]}" ]]
            then
                printf "${purple}%s/${bright}%s ${green}%s${reset}\n" "${fields[1]}" "${fields[2]}" "${fields[3]}"
            fi
            printf '    /%s\n' "${fields[4]}"
            pkg="${fields[2]}"
        done
    fi
}
...
ノート: The files database of pacman is separate from the normal sync database and it needs to be fetched using pacman -Fy. See pacman#Search for a package that contains a specific file for details.

For an alternative using pkgfile, see #pkgfile "command not found" handler.

サードパーティ拡張

設定フレームワーク

  • oh-my-zsh は Zsh の設定を管理するための、人気のあるコミュニティドリブンなフレームワークです。便利な関数、ヘルパー、プラグイン、テーマが山ほどバンドルされています。
  • Prezto - Instantly Awesome Zsh (AUR の prezto-gitAUR でインストール可能) は Zsh の設定フレームワークです。デフォルトでリッチなコマンドラインインターフェース環境を構築するモジュール・エイリアス・関数・自動補完・プロンプトテーマが付いています。
  • Zim (AUR の zsh-zim-gitAUR でインストール可能) は、驚異的な速度とモジュラー拡張機能を備えたZsh構成フレームワークです。

プラグインマネージャー

  • Antibody — Antigen に似たパフォーマンス重視のプラグインマネージャー
https://github.com/getantibody/antibody || antibodyAUR
  • zinit (previously "zplugin") — 柔軟で高速な Zsh プラグインマネージャー
http://github.com/zdharma/zinit || zsh-zplugin-gitAUR
  • zr — Rust で書かれたシンプルで高速なプラグインマネージャー
https://github.com/jedahan/zr || zr-gitAUR
  • sheldon — Rust で書かれた高速で柔軟なプラグインマネージャー
https://github.com/rossmacarthur/sheldon || sheldon-binAUR
  • zpm — キャッシュを生成し柔軟で高速なプラグインマネージャー
https://github.com/zpm-zsh/zpm || zpm-gitAUR
  • Antigen — oh-my-zsh と vundle に触発された Zsh のプラグインマネージャー ABANDONED
https://github.com/zsh-users/antigen || antigen-gitAUR
  • zgen — Zsh 用の軽量でシンプルなプラグインマネージャー ABANDONED
https://github.com/tarjoilija/zgen || zgen-gitAUR
  • zplug — Zsh 用の次世代プラグインマネージャー ABANDONED
https://github.com/zplug/zplug || zplugAUR

Fish のようなシンタックスハイライト

Fish には強力なシェルシンタックスハイライトがあります。これを zsh で使うには、公式リポジトリから zsh-syntax-highlighting をインストールして以下を zshrc に追加します:

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

"command not found" フック

pkgfile には、認識できないコマンドを入力したときに、自動的に公式リポジトリを検索する command_not_found_handler 関数を提供する Zsh スクリプトファイルが含まれています。

有効にするには、スクリプトを source する必要があります。例:

~/.zshrc
source /usr/share/doc/pkgfile/command-not-found.zsh
ノート: pkgfile データベースの更新が必要な場合があります。pkgfile#Installation で詳細をご確認ください。

アンインストール

Zsh があなたに合わないと感じて Bash に戻りたいときは、Zsh パッケージを削除する前に必ず、まずデフォルトシェルを変更して下さい。

警告: 以下の手順に従わないと、あらゆる種類の問題が発生します。ユーザーはシェルプログラムを使用できなくなります。

ターミナルで次のコマンドを root で実行して下さい:

# chsh -s /bin/bash user

Zsh を使っている全てのユーザーで実行して下さい。

これで安全に Zsh パッケージを削除することができます。

以上を行わなかった場合、root で /etc/passwd を編集することで Bash にデフォルトシェルを戻すことができます。

警告: ユーザー情報を編集するときは、不適切な形式のエントリを防ぐため、 vipw を使用することを 強く お勧めします。

例:

編集前:

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

編集後:

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

参照