如何在调用脚本文件时提示建议

时间:2014-02-06 11:33:16

标签: linux bash shell scripting

我必须为linux-box编写一个脚本,它从命令行获取输入 sudo build_all.sh -vmware yes|no nic bridged|host_only -ipaddress xx.xx.xx.xx|dhcp -arch=ARM|x86,我想知道输入输入时是否有办法我可以得到建议。 对于Ex。

如果我输入sudo build_all.sh并按Tab,我会在-vmware再次输入我-vmware Tab之后获得Yes之类的建议1}} No

有什么办法吗?

2 个答案:

答案 0 :(得分:1)

这称为bash完成。您可以在/etc/bash_completion.d/中找到许多示例。 bash_completion函数需要先加载到shell中才能运行。这是一个让你入门的例子

# Bash completion must to be loaded when shell starts
# Recommended location is /etc/bash_completion.d/build_all.sh
# or added to ~/.bashrc
# Then load with . /etc/bash_completion.d/build_all.sh
# or with . ~/.bashrc
# New instances of bash will have already sourced it. 
# The file name build_all.sh may be too common, and result in unwanted tab
# completion for build_all.sh from other projects. 

_build_all.sh(){
    local cur
    COMPREPLY=()
    _get_comp_words_by_ref cur

    case  $COMP_CWORD in
        1) COMPREPLY=( $( compgen -W '-vmware' -- "$cur" ) ) ;;
        2) COMPREPLY=( $( compgen -W 'no yes' -- "${COMP_WORDS[COMP_CWORD]}" ) ) ;;

        3) COMPREPLY=( $( compgen -W '-nic' -- "$cur" ) ) ;;
        4) COMPREPLY=( $( compgen -W 'host_only bridged' -- "${COMP_WORDS[COMP_CWORD]}" ) ) ;;

        5) COMPREPLY=( $( compgen -W '-ipaddress' -- "$cur" ) ) ;;
        6) COMPREPLY=( $( compgen -W 'dhcp xx.xx.xx.xx' -- "${COMP_WORDS[COMP_CWORD]}" ) ) ;;

        7) COMPREPLY=( $( compgen -W '-arch' -- "$cur" ) ) ;;
        8) COMPREPLY=( $( compgen -W 'x86 ARM' -- "${COMP_WORDS[COMP_CWORD]}" ) ) ;;
    esac
    return 0

} &&
complete -F _build_all.sh build_all.sh

答案 1 :(得分:0)

有一个名为whiptail的程序可以在文本模式下执行“GUI”对话框。

http://www.techrepublic.com/blog/linux-and-open-source/how-to-use-whiptail-to-write-interactive-shell-scripts/