我必须为 linux-box 编写一个从命令行获取输入的脚本sudo build_all.sh -vmware yes|no nic bridged|host_only -ipaddress xx.xx.xx.xx|dhcp -arch=ARM|x86
,我想知道是否有办法在输入时得到建议。 例如。
如果我输入sudo build_all.sh
并按Tab
,我会得到像-vmware
这样的建议,输入后-vmware
我再次树Tab
我为Yes
No
而提议。
有什么办法吗?
这称为 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
有一个名为whiptail
的程序可以在文本模式下执行"GUI"对话框。
http://www.techrepublic.com/blog/linux-and-open-source/how-to-use-whiptail-to-write-interactive-shell-scripts/