假设我有一堆 if 语句,其形式如下:
if(设置了某些标志变量/参数)然后 执行另一个命令或 bash 脚本
这维护起来有点麻烦,所以我想知道是否有其他方法可以做到这一点。而这个guide对于node.js,我想知道是否可以在bash中实现类似的东西
最佳答案
我想知道您是否正在寻找这样的东西:
#!/bin/bash
# initialize global options
debug=false
verbose=0
main() {
local OPTIND
while getopts :hdv: opt; do
case $opt in
h) show_help; exit ;;
d) debug=true ;;
v) verbose=$OPTARG;;
:) echo "error: missing argument for -$OPTARG"; exit 1;;
?) echo "error: unknown option -$OPTARG"; exit 1 ;;
esac
done
shift $((OPTIND-1))
if [[ -z $1 ]]; then
echo "error: missing subcommand"
show_help
exit 1
fi
case $1 in
bar|baz)
# invoke the command with the arguments
"$@" ;;
*) echo "error: unknown subcommand $1"; exit 1;;
esac
}
show_help() {
echo "usage: $(basename "$0") [global opts] subcommand [local opts and args]"
echo "... more details..."
}
bar() {
echo "you called $FUNCNAME with args $*"
}
baz() {
echo "this is baz"
local OPTIND
while getopts :ab opt; do
case $opt in
a|b) echo "you selected option $opt";;
?) echo "unknown option -$OPTARG";;
esac
done
if $debug; then echo "some debug message"; fi
(( verbose > 0 )) && echo "some verbose message"
}
main "$@"
关于Bash 脚本命令处理程序替换长 if 链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50973208/