gpt4 book ai didi

linux - 带有参数值和可选标志的 Bash 脚本

转载 作者:行者123 更新时间:2023-12-04 16:18:06 25 4
gpt4 key购买 nike

我正在编写一个 bash 脚本,它依赖于通过参数提供的许多值并提供可选的( bool 值)标志。
基于 this page 上的示例,我已经扩展了脚本,使用 -h选项,以下内容:

human=false

while getopts u:a:f:h: flag
do
case "${flag}" in
u) username=${OPTARG};;
a) age=${OPTARG};;
f) fullname=${OPTARG};;
h) human=true;;
esac
done

if $human; then
echo "Hello human"
else
echo "You're not human"
fi

echo "Username: $username";
echo "Age: $age";
echo "Full Name: $fullname";
问题在于, -h参数需要一个值,而它应该作为标志处理:
bash test.sh -u asdf -h
test.sh: option requires an argument -- h
You're not human
Username: asdf
Age:
Full Name:
如何在 bash 脚本中使用带有值和标志的两个参数?

最佳答案

您应该更换 getopts u:a:f:h:getopts u:a:f:h .
删除 :你告诉getopts那个h没有额外的参数。

关于linux - 带有参数值和可选标志的 Bash 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69657157/

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