プログラミング

Bash completeコマンドでオートコンプリートを実装する

Linuxパソコン・サーバー、UbuntuでのBash言語コマンドラインで、completeコマンドでオートコンプリートを実装する方法について紹介します。

補完ともいいますね。タブ補完。英語だとオートコンプリートになります。便利な機能ですね。

さて、そんなオートコンプリートはどうやって実装すればいいのでしょうか。

fzfを使ってカスタマイズドなオートコンプリートを実装している方もいるかもしれませんが、fzfはfzfで、goのくせに重いし、ちょっとした実装であれば大げさすぎます。

ちょっと独自関数実装して、その関数でタブ補完したときに、typeコマンド同様、コマンドや関数をタブ補完してくれるだけでいいんだけどなー。
cdコマンドのタブ補完と同じような候補を出したいなぁ、なんて場合。

types()という独自関数を実装して、type同様、コマンドを候補としてタブ補完したい場合は、以下。

complete -A command types

https://yuis.xsrv.jp/images/ss/ShareX_ScreenShot_20e31035-78f2-48c0-876f-285d95b9cef7.png

cdコマンドのタブ補完と同じような候補を出したいなぁ、なんて場合。

complete -F _cd hoge

ここらへんが使えそうです。

-A action
The action may be one of the following to generate a list of possible completions:

-C command
command is executed in a subshell environment, and its output is used as the possible completions.

-F function
The shell function function is executed in the current shell environment. When it is executed, $1 is the name of the command whose arguments are being completed, $2 is the word being completed, and $3 is > the word preceding the word being completed, as described above (see Programmable Completion). When it finishes, the possible completions are retrieved from the value of the COMPREPLY array variable.

-Aオプションでは、テンプレート的な感じで手軽にタブ補完候補を割当できます。値は以下からお好きなのを。

alias
arrayvar
binding
builtin
command
directory
disabled
enabled
export
file
function
group
helptopic
hostname
job
keyword
running
service
setopt
shopt
signal
stopped
user
variable

詳しい説明は以下リファレンスから。

Bash Reference Manual
bash – What’s the use of complete command? – Ask Ubuntu

bash_completionファイルを見るとわかりますが、コードが複雑で読む気にならないですね。type _cdでさえ何書いてあるのかわからんし…。

簡単なオートコンプリートは今回紹介したやり方がいいと思いますが、複雑なオートコンプリートを実装したい方は、fzfを使うことをおすすめします。

fzfでBashコマンドラインをめっちゃ便利にする

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です