具有自动完成功能中的用户定义功能的Bash脚本 [英] Bash script with user defined functions in autocomplete

查看:90
本文介绍了具有自动完成功能中的用户定义功能的Bash脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要我的bash脚本来从用户那里获取函数名称.该脚本应通过自动完成在同一bash脚本文件中定义的功能来为用户提供帮助.

I need my bash script to get function names from user. The script should assist the users by auto completing the functions defined inside the same bash script file.

例如:

myBash.sh

myBash.sh

#!/usr/bash
function func1()
{
    echo "In func1 func"
}

function func2()
{
    echo "In func2 func"
}

function myFunc1()
{
    echo "In myFunc1 func"
}

while [ 1 ]
do
    echo -n "cmd>"
    read $userCmd
    $userCmd
done

]$ ./mybash.sh
cmd> my<tab><tab>
myFunc1

cmd> func<tab><tab>
func1 func2

这是我的必需输出. 该如何陪伴?

This is my required output. How to accompany this?

推荐答案

此替代方法应该可以解决问题.

This workaround should do the trick.

#!/bin/bash

func1() {
    echo "You are in func1: $@"
}

func2() {
    echo "You are in func2: $@"
}

myFunc1() {
    echo "You are in myFunc1: $@"
}

#use: autocomplete "word1 word2 ..."
autocomplete() {
     #we only try to autocomplete the last word so we keep a record of the rest of the input
     OTHER_WORDS="${READLINE_LINE% *} " 
     if [[ ${#OTHER_WORDS} -ge ${#READLINE_LINE} ]]; then #if there is only 1 word...
         OTHER_WORDS="" 
     fi

     #the -W flag tells compgen to read autocomplete from the 1st argument provided
     #we then evaluate the last word of the current line through compgen
     AUTOCOMPLETE=($(compgen -W $1 "${READLINE_LINE##* }"))
     if [[ ${#AUTOCOMPLETE[@]} == 1 ]]; then #if there is only 1 match, we replace...
        READLINE_LINE="$OTHER_WORDS${AUTOCOMPLETE[0]} "
        READLINE_POINT=${#READLINE_LINE}     #we set the cursor at the end of our word
     else
        echo -e "cmd> $READLINE_LINE\n${AUTOCOMPLETE[@]}" #...else we print the possibilities
     fi
}

MYFUNC="func1 func2 myFunc1" #here we list the values we want to allow autocompletion for
set -o emacs     #we do this to enable line edition
bind -x '"\t":"autocomplete \$MYFUNC"';   #calls autocomplete when TAB is pressed
while read -ep "cmd> "; do
    history -s $REPLY    #history is just a nice bonus
    eval ${REPLY}
done

尝试:

]$ ./mybash.sh
cmd> my<tab>
cmd> myFunc1

cmd> func<tab>
func1 func2

cmd> func1 hello, world!
You are in func2: hello, world!

cmd> func1 my<tab>
cmd> func1 myFunc1

如我之前的评论中所述,请查看

As mentioned in my previous comment, have a look at this question. It uses a nice trick to auto detect all inner functions in order to use it as auto-complete values.

这篇关于具有自动完成功能中的用户定义功能的Bash脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆