首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在自动完成中具有用户定义函数的Bash脚本

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

Stack Overflow用户
提问于 2014-07-16 13:35:32
回答 1查看 1.7K关注 0票数 3

我需要bash脚本从用户那里获得函数名。脚本应该通过自动完成在同一个bash脚本文件中定义的函数来帮助用户。

例:

myBash.sh

代码语言:javascript
复制
#!/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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-07-16 15:59:13

这个解决办法应该能起作用。

代码语言:javascript
复制
    #!/bin/bash

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

    myFunc1() {
        echo "You are in myFunc1: $@"
    }
    
    # usage: autocomplete "word1 word2 ..."
    autocomplete() {
         # try to autocomplete the last word, and 
         # 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, then we
         # 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, substitute it
             READLINE_LINE="$OTHER_WORDS${AUTOCOMPLETE[0]} "
             # position the cursor at the end of the word
             READLINE_POINT=${#READLINE_LINE}
         else
             #...otherwise print the possibilities
             echo -e "cmd> $READLINE_LINE\n${AUTOCOMPLETE[@]}" 
         fi
    }
    
    # list the values to be autocompleted
    MYFUNC="func1 func2 myFunc1" 
    # enable line editing
    set -o emacs
    # call autocomplete when TAB is pressed
    bind -x '"\t":"autocomplete \$MYFUNC"';   
    while read -ep "cmd> "; do
        # history is just a nice bonus
        history -s $REPLY
        eval ${REPLY}
    done

试试看:

代码语言:javascript
复制
    ]$ ./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。它使用一个很好的技巧来自动检测所有内部函数,以便将其用作自动完成的值。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24782266

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档