gpt4 book ai didi

linux - 具有自动完成功能的用户定义函数的 Bash 脚本

转载 作者:太空狗 更新时间:2023-10-29 11:19:09 35 4
gpt4 key购买 nike

我需要我的 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

这是我需要的输出。如何陪伴?

最佳答案

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

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

尝试一下:

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

关于linux - 具有自动完成功能的用户定义函数的 Bash 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24782266/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com