gpt4 book ai didi

Bash 脚本参数

转载 作者:行者123 更新时间:2023-11-29 09:51:16 25 4
gpt4 key购买 nike

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

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

./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 "$1" = ""; then
exit
fi

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

但它根本不起作用。

最佳答案

假设您的强制参数出现在最后,那么您应该尝试以下代码:[内联评论]

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))
[ "$1" = "--" ] && shift

# test: there is at least one more argument left

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

echo "$1"
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="${1}"
[[ "${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))
[ "$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

关于Bash 脚本参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42020356/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com