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

Bar*_*mir 2 bash arguments

我写了一个 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
Run Code Online (Sandbox Code Playgroud)

Kus*_*nda 5

只接受单个参数的脚本,该参数必须是abc

#!/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
Run Code Online (Sandbox Code Playgroud)

如果您想要进行正确的选项解析并希望接受-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.
Run Code Online (Sandbox Code Playgroud)

测试:

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

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

$ ./script -d -a -- -c -b
Option -d: -a
Further operands:
        -c
        -b
Run Code Online (Sandbox Code Playgroud)