自定义linux命令参数补全以提高工作效率

LUOPING0 2020-03-28

我们在使用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镜像或者容器的名称,非常方便

[ ~]# dockerq 
images  pull    run     start   
[ ~]# 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       
[ ~]# dockerq run ^C
[ ~]# 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
[ ~]# dockerq images

   希望这篇文章对你有帮助。

相关推荐