Bash 脚本命令处理程序替换长 if 链

标签 bash

假设我有一堆 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/

相关文章:

linux - 这个组合命令 :() { :|:& }; : work? (CAUTION : don't try, 导致系统停止)

bash - Dockerfile 中需要冗余 eval $(opam env)

string - 在 bash 上使用 test 命令比较两个字符串时,由于特殊字符 * 导致出现 "test: too many arguments"消息

bash - 管道问题在 sed 中查找(查找并替换)

c++ - 如何在 bazel/googletest 中使用环境变量

c++ - 如何将 Google 测试输出打印到文本文件?

linux - 如何使用 sed 或其他 linux 工具有条件地交换两行?

linux - grep/根据第一个文件中的列表从第二个文件中获取字符串

linux - 必须在 macbook 上运行导出命令才能使用 PhoneGap 创建 Android 项目

bash - 我如何使用 bash (grep/sed/etc) 在两个时间戳之间获取日志文件的一部分?