2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

ubuntuのzshでbashのようにコマンドの提案を行う

Last updated at Posted at 2021-04-19

ubuntuのbashで存在しないコマンドを実行した場合、

$ ruby

コマンド 'ruby' が見つかりません。次の方法でインストールできます:

sudo snap install ruby  # version 3.0.0, or
sudo apt  install ruby  # version 1:2.7+1

他のバージョンについては 'snap info ruby' を確認してください。

のようになる。だがzshでは

$ ruby
zsh: command not found: ruby

だけしかメッセージが表示されないため、いつもubuntu {パッケージ名} インストールでggっている。

コマンドが見つからないときの挙動

調べてみるとコマンドが見つからないときには関数command_not_found_handleが実行されるようだ。関数の定義はdeclareで調べられるらしい。実行してみると

$ declare -f command_not_found_handle
command_not_found_handle ()
{ 
    if [ -x /usr/lib/command-not-found ]; then
        /usr/lib/command-not-found -- "$1";
        return $?;
    else
        if [ -x /usr/share/command-not-found/command-not-found ]; then
            /usr/share/command-not-found/command-not-found -- "$1";
            return $?;
        else
            printf "%s: command not found\n" "$1" 1>&2;
            return 127;
        fi;
    fi
}

となる。つまり、/usr/lib/command-not-foundがあればそれを、/usr/share/command-not-found/command-not-foundがあればそれを、両者ともなければ単純なメッセージを表示するという内容である。つまり、これを~/.zshrcにコピペすれば、

$ ruby

コマンド 'ruby' が見つかりません。次の方法でインストールできます:

sudo snap install ruby  # version 3.0.0, or
sudo apt  install ruby  # version 1:2.7+1

他のバージョンについては 'snap info ruby' を確認してください。

成功!!

/usr/lib/command-not-found

筆者の環境では、/usr/lib/command-not-foundが実行されるようである。これのhelpを表示してみると、

Usage: command-not-found [オプション] <コマンド名>

Options:
  --version             show program's version number and exit
  -h, --help            show this help message and exit
  -d DATA_DIR, --data-dir=DATA_DIR
                        データフィールドの検索に次のパスを使う
  --ignore-installed, --ignore-installed
                        ローカルのバイナリーを無視して、利用可能なパッケージを表示する
  --no-failure-msg      '<コマンド名>: コマンドが見つかりません' を出力しない

と、表示される。また、ggってみると、環境変数COMMAND_NOT_FOUND_INSTALL_PROMPTをyに設定すると、インストールできる項目が一つしかない場合に、インストールするか聞いてくれます。
Screenshot_20210419_210057.png

参考

2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?