Bash 个脚本参数

Bash script arguments

我正在尝试将参数传递给我编写的脚本,但无法正确处理。

我想要的是一个不带标志的强制参数,和两个带标志的可选参数,所以可以这样调用:

./myscript mandatory_arg -b opt_arg -a opt_arg

./myscript mandatory_arg -a opt_arg
./myscript mandatory_arg -b opt_arg

我查看了 getopts 并得到了这个:

while getopts b:a: option
do
    case "${option}"
    in
        b) MERGE_BRANCH=${OPTARG};;
        a) ACTION=${OPTARG};;
    esac
done

if "" = ""; then
    exit
fi

echo ""
echo "$MERGE_BRANCH"
echo "$ACTION"

但是一点用都没有。

假设你的 mandatory argument 出现在 last,那么你应该尝试下面的代码:[comments inline]

OPTIND=1
while getopts "b:a:" option
do
    case "${option}"
    in
        b) MERGE_BRANCH=${OPTARG};;
        a) ACTION=${OPTARG};;
    esac
done

# reset positional arguments to include only those that have not
# been parsed by getopts

shift $((OPTIND-1))
[ "" = "--" ] && shift

# test: there is at least one more argument left

(( 1 <= ${#} )) || { echo "missing mandatory argument" 2>&1 ; exit 1; };

echo ""
echo "$MERGE_BRANCH"
echo "$ACTION"

结果:

~$ ./test.sh -b B -a A test
test
B
A
~$ ./tes.sh -b B -a A
missing mandatory argument

如果你真的想让强制参数出现第一个,那么你可以做以下事情:

MANDATORY=""
[[ "${MANDATORY}" =~ -.* ]] && { echo "missing or invalid mandatory argument" 2>&1; exit 1; };

shift # or, instead of using `shift`, you can set OPTIND=2 in the next line   
OPTIND=1
while getopts "b:a:" option
do
    case "${option}"
    in
        b) MERGE_BRANCH=${OPTARG};;
        a) ACTION=${OPTARG};;
    esac
done

# reset positional arguments to include only those that have not
# been parsed by getopts

shift $((OPTIND-1))
[ "" = "--" ] && shift

echo "$MANDATORY"
echo "$MERGE_BRANCH"
echo "$ACTION"

结果如下:

~$ ./test.sh test -b B -a A
test
B
A
~$ ./tes.sh -b B -a A
missing or invalid mandatory argument