在自动完成中使用用户定义函数的Bash脚本

时间:2014-07-16 13:35:33

标签: linux bash shell

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

例如:

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

这是我要求的输出。 怎么陪这个?

1 个答案:

答案 0 :(得分:1)

这种解决方法应该可以解决问题。

#!/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

如我之前的评论所述,请查看this question。它使用一个很好的技巧来自动检测所有内部函数,以便将其用作自动完成值。