默認fish能自動補全的命令已經相當多了,常見的apt-get,rpm等都沒問題,但今天卻發現沒有lsusb的補全規則,查看了下文檔,發現規則比bash-completion簡單不少,記錄下~
簡單補全
1. 建立自動補全規則文件
默認自動補全路徑由全局變量$fish_complete_path定義
我選取了位置/usr/share/fish/completions,在其中建立lsusb.fish文件
2. 書寫補全規則
先查看下lsusb有哪些選項
fish自帶complete命令用于定義補全規則
使用方法是:
complete -c 命令 -s 短選項 -l 長選項 --description "描述"
譬如我想有lsusb的-v(–verbose)選項的自動補全,就可以這樣寫:
complete -c lsusb -s v -l verbose --description "Increase verbosity (show descriptors)"
這里:
-c lsusb 是我希望添加補全的命令 -s 后接短選項,類似-v形式
-l 后接長選項,類似--verbose形式
--description 是選項的解釋,可有可無
仿照例子將如下命令添加到lsusb.fish文件中
complete -c lsusb -s v -l verbose --description "Increase verbosity (show descriptors)"
complete -c lsusb -s s --description "Show only devices with specified device and/or bus numbers (in decimal)"
complete -c lsusb -s d --description "Show only devices with the specified vendor and product ID numbers (in hexadecimal)"
complete -c lsusb -s D -l device --description "Selects which device lsusb will examine"
complete -c lsusb -s t -l tree --description "Dump the physical USB device hierarchy as a tree"
complete -c lsusb -s V -l version --description "Show version of program"
complete -c lsusb -s h -l help --description "Show usage and help"
如此輸入lsusb -敲tab鍵就會自動補全了
高級補全
一些命令不光有基于-或–如此形式的選項補全,還有自身特點特定的補全,如mount的掛載點補全,su的用戶補全,ssh的主機補全,這是怎么做到的呢? 還以lsusb為例,lsusb -s 001:001 是列出第一個bus的第一個device信息,我希望當輸入lsusb -s 時,按下tab會列出當前主機所有bus和device讓我選擇
complete提供了-x和-a來實現這樣的高級補全
complete -x -c lsusb -s s -a '(__fish_complete_usb)' --description "Show only devices with specified device and/or bus numbers (in decimal)"
-x 告訴complete不要用tab默認的文件補全,而是要用-a告訴的參數來補全
-a “參數列表” 是一個列表,里面是complete參數補全的依據,這里我用__fish_complete_usb 來實時生成,而沒有寫死
函數__fish_complete_usb是由/usr/share/fish/functions/__fish_complete_usb.fish定義的,用來生成設備列表
function __fish_complete_usb
lsusb | awk '{print $2 ":" $4}'| cut -c1-7
end
如此lsusb -s就能基于總線設備號來補全了
補充:lsusb completion已經被fish官方采納,這是我貢獻的第一個開源項目,好高興!