自定義linux命令參數補全以提高工作效率【轉】

轉自:https://www.cnblogs.com/kingstarer/p/12586721.html

  我們在使用bash命令時,會經常使用二次tab鍵進行補齊。

      例如我們常用的telnet命令,在輸入二次tab鍵時,會列出當前系統配置的所有主機名,供選擇

# 輸入 telnet <Tab> <Tab>
[huangcihui:/home/huangcihui] telnet 
::1                      localhost                localhost4               localhost4.localdomain4  localhost6               localhost6.localdomain6  localhost.localdomain    
[huangcihui:/home/huangcihui] telnet 

     在輸入telnet參數過程中按回車,系統也會自動補全主機名

#輸入 telnet l<Tab>
[huangcihui:/home/huangcihui] telnet localhost

  其它常用命令,也會有這個功能。 例如systemctl,輸入二次tab鍵時會列出systemctl所有子命令參數

複製代碼
#systemctl <Tab><Tab>
[huangcihui:/home/huangcihui] systemctl 
add-requires           daemon-reexec          enable                 hybrid-sleep           kill                   list-units             reload-or-restart      set-property           suspend                
add-wants              daemon-reload          exit                   is-active              link                   mask                   reload-or-try-restart  show                   switch-root            
cancel                 default                force-reload           is-enabled             list-dependencies      poweroff               rescue                 show-environment       try-restart            
cat                    delete                 get-default            is-failed              list-jobs              preset                 reset-failed           snapshot               unmask                 
condreload             disable                halt                   isolate                list-sockets           reboot                 restart                start                  unset-environment      
condrestart            edit                   help                   is-system-running      list-timers            reenable               set-default            status                 
condstop               emergency              hibernate              kexec                  list-unit-files        reload                 set-environment        stop                   
[huangcihui:/home/huangcihui] systemctl 
複製代碼

  那麼,自己開發的程序,能不能實現Tab自動補全? 答案是肯定的,藉助bash的complete命令即可。

假設我們新寫了一個命令叫tel,我們想讓它實現telnet的被全主機名功能,用這個命令即可:complete -A hostname tel 效果如下:

[huangcihui:/home/huangcihui] complete -A hostname tel
[huangcihui:/home/huangcihui] #tel l<Tab>
[huangcihui:/home/huangcihui] tel localhost

  而像systemctl這種補全子命令的功能,要怎麼做呢? 下面我演示一下怎麼讓git命令實現子命令補全功能

[huangcihui:/home/huangcihui] complete -W "add checkout clone commit diff pull push status" git
[huangcihui:/home/huangcihui] #git <Tab>
[huangcihui:/home/huangcihui] git 
add       checkout  clone     commit    diff      pull      push      status    
[huangcihui:/home/huangcihui] git 

  complete還有更多複雜的用法,有興趣可以參考這篇文章

https://blog.csdn.net/koprvhdix/article/details/81036240
Linux Shell 命令自動補全(各方資料彙總補全版) Clockworkai

  下面是我使用complete命令幫我自定義的dockerq命令進行自動補全的函數

複製代碼
# 新建一個命令dockerq 用於快速操作docker
__dockerq()
{
        COMPREPLY=() # 清空候選列表
        local cur=${COMP_WORDS[COMP_CWORD]}; # 用戶輸入單詞賦值給cur
        local cmd=${COMP_WORDS[COMP_CWORD-1]}; # 用戶正在操作的命令或者子命令
    case $cmd in
    'dockerq')
                # 獲取docker所有命令
                # local cmdlist=$(docker --help|awk '{if ($1 == "Commands:") { v_showFlag = 1; next; } else if ($1 == "") v_showFlag = 0; if (v_showFlag) print $1;}')

                cmdlist="images pull start run"
                # 獲取以cul開頭的所有命令
                local wordlist="$(compgen -W "${cmdlist}" -- $cur)"
                
                # 給候選列表賦值
                COMPREPLY=( ${wordlist} ) ;;
    'images')
                #使用docker images獲取所有鏡像名稱
                local cmdlist=$(docker images|awk '{if (NR != 1) print $1;}')

                # 獲取以cul開頭的所有命令
                local wordlist="$(compgen -W "${cmdlist}" -- $cur)"
                
                # 給候選列表賦值
                COMPREPLY=( ${wordlist} ) ;;

    'run')
                #使用docker ps獲取所有容器名稱
                local cmdlist=$(docker ps -a|awk '{if (NR != 1) print $NF;}')

                # 獲取以cul開頭的所有命令
                local wordlist="$(compgen -W "${cmdlist}" -- $cur)"
                
                # 給候選列表賦值
                COMPREPLY=( ${wordlist} ) ;;
    '*')
                ;;
    esac
    if [[ "${COMP_WORDS[1]}" == "read" && ${COMP_CWORD} -eq 2 ]]; then
                local pro=($(pwd))
                cd /data
                compopt -o nospace
                COMPREPLY=($(compgen -d -f -- $cur))
                cd $pro
                fi
    return 0
}
complete -F  __dockerq dockerq
alias dockerq=docker
複製代碼

  使用dockerq命令時,按Tab鍵可以自動補齊docker鏡像或者容器的名稱,非常方便

複製代碼
[root@localhost ~]# dockerq 
images  pull    run     start   
[root@localhost ~]# dockerq run 
adoring_wozniak      charming_ptolemy     composetest_web_1    determined_hodgkin   exciting_cartwright  hardcore_mestorf     hungry_mclean        mystifying_cohen     nginx001             thirsty_franklin     
alptest1             composetest_redis_1  cpu_set_demo         example1             exp1                 heuristic_cannon     magical_cartwright   nginx                phpfpm               thirsty_merkle       
[root@localhost ~]# dockerq run ^C
[root@localhost ~]# dockerq images 
abh1nav/dockerui                        composetest_web                         feisky/nginx                            mysql                                   redis
alpine                                  docker/compose                          feisky/php-fpm                          nginx                                   todoapp
busybox                                 dockerinpractice/dockerfile-from-image  hello-world                             node                                    ubuntu
centurylink/dockerfile-from-image       dockerinpractice/docker-image-graph     lukapeschke/dfa                         python                                  wordpress
[root@localhost ~]# dockerq images 
複製代碼

   希望這篇文章對你有幫助。

~~積土成山,風雨興焉;積水成淵,蛟龍生焉;~~~
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章