2024/02/13 22:13:39

bashの補完機能

TABで入力補完すれば、typo も減る

通常の補完

(TAB)キーを押すことで、ディレクトリ名やファイル名を補完してくれる。

$ cat /home/bayashi/.bash(TAB)
.bash_history  .bashrc

とっても便利。

bash_completion

補完をさらに便利にしてくれるパッケージが bash_completion
CentOS は、デフォルトでは入っていないので yum でインストールする。

$ sudo yum install bash_completion

例えば、man の後でインストール済みコマンドの補完がきくようになる。

$ man user
useradd     userdel     userhelper  usermod     usernetctl  users

他にも気の利いた補完をしてくれる。

補完スクリプトの自作

補完スクリプトは以下のようなシンプルなスクリプトで作成することができる。

_appctrl()
{
    local opts cur prev
    opts=`ls ~/dev/`
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"

    if [ $COMP_CWORD = 1 ]; then
      COMPREPLY=( $( compgen -W "$opts"    -- $cur ))
    elif [ $COMP_CWORD = 2 ]; then
      COMPREPLY=( $( compgen -W "deploy status allstatus stop start restart" -- $cur ))
    fi
}
complete -F _appctrl appctrl

appctrl コマンドの引数を補完する。

$ appctrl (TAB)
BayaMo    MyApp     NoPaste

補完候補はアプリのリスト(ls ~/dev/)

$ appctrl MyApp (TAB)
allstatus  deploy     restart    start      status     stop

という風に便利になる。

サイト内検索