问题描述
是否可以为bash脚本实现子命令.我有这样的想法:
Is it possible to implement sub-commands for bash scripts. I have something like this in mind:
http://docs.python.org/dev/library/argparse.html#sub-commands
推荐答案
这是一种简单的不安全技术:
Here's a simple unsafe technique:
#!/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
}
"$@"
这非常酷,但是它并不限制子命令的内容.因此,您可能希望将最后一行替换为:
That's all very cool, but it doesn't limit what a subcommand could be. So you might want to replace the last line with:
if [[ $1 =~ ^(clean|help|args)$ ]]; then
"$@"
else
echo "Invalid subcommand $1" >&2
exit 1
fi
某些系统允许您在子命令前放置全局"选项.如果需要,可以在子命令执行之前放置一个 getopts
循环.在执行子命令之前,请记住先进行 shift
操作.同样,将 OPTIND
重置为1,以使子命令getopts不会混淆.
Some systems let you put "global" options before the subcommand. You can put a getopts
loop before the subcommand execution if you want to. Remember to shift
before you fall into the subcommand execution; also, reset OPTIND
to 1 so that the subcommands getopts doesn't get confused.
这篇关于bash的子命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!