AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / unix / 问题 / 677507
Accepted
Baran Aldemir
Baran Aldemir
Asked: 2021-11-15 10:33:42 +0800 CST2021-11-15 10:33:42 +0800 CST 2021-11-15 10:33:42 +0800 CST

如何有效地检查给 bash 脚本的参数?

  • 772

我写了一个 bash 脚本,但由于我是一个自学的 bash 菜鸟,我想问我是否可以更有效地检查给定的参数。我也用谷歌搜索过这个并检查了这里的主题,但到目前为止我看到的例子太复杂了。在 python3 中,有很多更简单的方法,但我想在 bash 中它有点复杂。

#!/bin/bash

ERR_MSG="You did not give the argument required"

if [[ ${1?$ERR_MSG} == "a" ]]; then
        echo "ABC"
elif [[ ${1?$ERR_MSG} == "b" ]]; then
        echo "123"
elif [[ ${1?$ERR_MSG} == "c" ]]; then
        echo ".*?"
else
    echo "You did not provide the argument correctly"
    exit 1
fi
bash arguments
  • 2 2 个回答
  • 2350 Views

2 个回答

  • Voted
  1. they
    2021-11-16T12:50:59+08:002021-11-16T12:50:59+08:00

    只接受一个参数的脚本,该参数必须是a、b或c:

    #!/bin/bash
    
    if [[ $# -ne 1 ]]; then
        echo 'Too many/few arguments, expecting one' >&2
        exit 1
    fi
    
    case $1 in
        a|b|c)  # Ok
            ;;
        *)
            # The wrong first argument.
            echo 'Expected "a", "b", or "c"' >&2
            exit 1
    esac
    
    # rest of code here
    

    如果您想进行正确的选项解析并希望接受-a, -b, 或-c作为不带参数-d的选项,以及作为带参数的选项。

    #!/bin/bash
    
    # Default values:
    opt_a=false
    opt_b=false
    opt_c=false
    opt_d='no value given'
    
    # It's the : after d that signifies that it takes an option argument.
    
    while getopts abcd: opt; do
        case $opt in
            a) opt_a=true ;;
            b) opt_b=true ;;
            c) opt_c=true ;;
            d) opt_d=$OPTARG ;;
            *) echo 'error in command line parsing' >&2
               exit 1
        esac
    done
    
    shift "$(( OPTIND - 1 ))"
    
    # Command line parsing is done now.
    # The code below acts on the used options.
    # This code would typically do sanity checks,
    # like emitting errors for incompatible options, 
    # missing options etc.
    
    "$opt_a" && echo 'Got the -a option'
    "$opt_b" && echo 'Got the -b option'
    "$opt_c" && echo 'Got the -c option'
    
    printf 'Option -d: %s\n' "$opt_d"
    
    if [[ $# -gt 0 ]]; then
        echo 'Further operands:'
        printf '\t%s\n' "$@"
    fi
    
    # The rest of your code goes here.
    

    测试:

    $ ./script -d 'hello bumblebee' -ac
    Got the -a option
    Got the -c option
    Option -d: hello bumblebee
    
    $ ./script
    Option -d: no value given
    
    $ ./script -q
    script: illegal option -- q
    error in command line parsing
    
    $ ./script -adboo 1 2 3
    Got the -a option
    Option -d: boo
    Further operands:
            1
            2
            3
    

    选项解析在第一个非选项参数处终止,或者在--. 请注意,因为-d需要一个参数,-a所以在以下示例中被视为该参数:

    $ ./script -d -a -- -c -b
    Option -d: -a
    Further operands:
            -c
            -b
    
    • 1
  2. Best Answer
    LincolnP
    2021-11-15T11:43:12+08:002021-11-15T11:43:12+08:00

    将此代码复制到文件中。(不要忘记chmod +x)这应该可以满足您的需求。

    #!/bin/bash
    VERSION="0.0.1"
    ACCEPTED_SERVER="server"
    ACCEPTED_USER="user"
    
    usage()
    {
        echo " $(basename $0) [-v] [-h] -u user -s server"
        exit
    }
    
    version()
    {
        echo "Current version: $VERSION"
    }
    
    get_opts()
    {
        while [[ $# -gt 0 ]]
        do
            key="$1"
            case $key in
                -u|--user)
                    shift
                    USER="$1"
                    shift
                    ;;
                -s|--server)
                    shift
                    SERVER="$1"
                    shift
                    ;;
                -h|--help)
                    usage
                    exit
                    ;;
                -v|--version)
                    version
                    exit
                ;;
            esac
        done
    }
    
    # echo " arguments: $#"
    get_opts $*
    if [ $# -gt 4 ] || [ $# -lt 1 ]; then
        usage
    fi
    echo "$SERVER -- $ACCEPTED_SERVER"
    if ! [ "$SERVER" = "$ACCEPTED_SERVER" ]; then
        echo "Wrong server: $SERVER"
        echo "Try with user: $ACCEPTED_SERVER"
        usage
    else
        echo "Correct server: $SERVER"
    
    fi
    if ! [ "$USER" = "$ACCEPTED_USER" ]; then
        echo "Wrong user: $USER"
        echo "Try with user: $ACCEPTED_USER"
        usage
    else
        echo "Correct user: $USER"
    fi
    
    echo "Correct! - Server: $SERVER - User: $USER"
    

    然后可以添加功能用法、版本等。

    usage()
    {
        echo "[-v] [-h] [-u user] [-s server] task"
    }
    
    • -1

相关问题

  • 通过命令的标准输出以编程方式导出环境变量[重复]

  • 从文本文件传递变量的奇怪问题

  • 虽然行读取保持转义空间?

  • `tee` 和 `bash` 进程替换顺序

  • 运行一个非常慢的脚本直到它成功

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    模块 i915 可能缺少固件 /lib/firmware/i915/*

    • 3 个回答
  • Marko Smith

    无法获取 jessie backports 存储库

    • 4 个回答
  • Marko Smith

    如何将 GPG 私钥和公钥导出到文件

    • 4 个回答
  • Marko Smith

    我们如何运行存储在变量中的命令?

    • 5 个回答
  • Marko Smith

    如何配置 systemd-resolved 和 systemd-networkd 以使用本地 DNS 服务器来解析本地域和远程 DNS 服务器来解析远程域?

    • 3 个回答
  • Marko Smith

    dist-upgrade 后 Kali Linux 中的 apt-get update 错误 [重复]

    • 2 个回答
  • Marko Smith

    如何从 systemctl 服务日志中查看最新的 x 行

    • 5 个回答
  • Marko Smith

    Nano - 跳转到文件末尾

    • 8 个回答
  • Marko Smith

    grub 错误:你需要先加载内核

    • 4 个回答
  • Marko Smith

    如何下载软件包而不是使用 apt-get 命令安装它?

    • 7 个回答
  • Martin Hope
    user12345 无法获取 jessie backports 存储库 2019-03-27 04:39:28 +0800 CST
  • Martin Hope
    Carl 为什么大多数 systemd 示例都包含 WantedBy=multi-user.target? 2019-03-15 11:49:25 +0800 CST
  • Martin Hope
    rocky 如何将 GPG 私钥和公钥导出到文件 2018-11-16 05:36:15 +0800 CST
  • Martin Hope
    Evan Carroll systemctl 状态显示:“状态:降级” 2018-06-03 18:48:17 +0800 CST
  • Martin Hope
    Tim 我们如何运行存储在变量中的命令? 2018-05-21 04:46:29 +0800 CST
  • Martin Hope
    Ankur S 为什么 /dev/null 是一个文件?为什么它的功能不作为一个简单的程序来实现? 2018-04-17 07:28:04 +0800 CST
  • Martin Hope
    user3191334 如何从 systemctl 服务日志中查看最新的 x 行 2018-02-07 00:14:16 +0800 CST
  • Martin Hope
    Marko Pacak Nano - 跳转到文件末尾 2018-02-01 01:53:03 +0800 CST
  • Martin Hope
    Kidburla 为什么真假这么大? 2018-01-26 12:14:47 +0800 CST
  • Martin Hope
    Christos Baziotis 在一个巨大的(70GB)、一行、文本文件中替换字符串 2017-12-30 06:58:33 +0800 CST

热门标签

linux bash debian shell-script text-processing ubuntu centos shell awk ssh

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve