是否可以为bash脚本实现子命令。我有类似的想法:
http://docs.python.org/dev/library/argparse.html#sub-commands
答案 0 :(得分:8)
这是一种简单的不安全技术:
#!/bin/bash
clean() {
echo rm -fR .
echo Thanks to koola, I let you off this time,
echo but you really shouldn\'t run random code you download from the net.
}
help() {
echo Whatever you do, don\'t use clean
}
args() {
printf "%s" options:
while getopts a:b:c:d:e:f:g:h:i:j:k:l:m:n:o:p:q:r:s:t:u:v:w:x:y:z: OPTION "$@"; do
printf " -%s '%s'" $OPTION $OPTARG
done
shift $((OPTIND - 1))
printf "arg: '%s'" "$@"
echo
}
"$@"
这一切都非常酷,但并不限制子命令的含义。因此,您可能希望将最后一行替换为:
if [[ $1 =~ ^(clean|help|args)$ ]]; then
"$@"
else
echo "Invalid subcommand $1" >&2
exit 1
fi
某些系统允许您在子命令之前添加“全局”选项。如果需要,可以在子命令执行之前放置getopts
循环。在进入子命令执行之前,请记住shift
;此外,将OPTIND
重置为1,以便子命令getopts不会混淆。