2014-07-16 2 views
3

사용자로부터 함수 이름을 가져 오려면 bash 스크립트가 필요합니다. 스크립트는 동일한 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 

이 내 필요한 출력됩니다. 동행 방법?

+0

반답 : 입력을 처리하기 위해'readline'을 사용하려면'-e' 옵션을'read'로 사용하십시오 (명령 완료 포함). 좀 더 어려운 부분은'readline'을 사용하여 명령 이름의 잠재적 완료로 국지적으로 정의 된 함수 만 사용하는 것입니다. – chepner

+1

분명히 그것은 진짜 고통이며, 나는 [이 답변] (http://stackoverflow.com/questions/4726695/bash-and-readline-tab-completion-in-a-)에 설명 된 버그가 있는지 알지 못합니다. user-input-loop)이 수정되었습니다. – Aserre

+0

@Ploutox - 해당 게시물을 검색했지만 찾으려는 방법을 기억하지 못했습니다. 그 버그는 내가 이것을 시도 할 때 너무 나를 괴롭힌다. 위대한 발견! – ghoti

답변

1

이 해결 방법은 트릭을 수행해야합니다.

#!/bin/bash 

func1() { 
    echo "You are in func1: [email protected]" 
} 

func2() { 
    echo "You are in func2: [email protected]" 
} 

myFunc1() { 
    echo "You are in myFunc1: [email protected]" 
} 

#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를 보라. 자동 완성 값으로 사용하기 위해 모든 내부 함수를 자동으로 탐지하는 멋진 트릭을 사용합니다.

+0

고맙습니다 @Ploutox. 이것은 나를 위해 완벽하게 작동합니다 :) – Ashwin

관련 문제