gpt4 book ai didi

linux - getopts 没有将我的选项发送到标准输出

转载 作者:太空宇宙 更新时间:2023-11-04 10:35:43 28 4
gpt4 key购买 nike

我开始尝试使用 getopts,但遇到了一些错误。当我输入无效选项(例如 -A)时,程序输出不是它需要的。

#!/bin/bash

function usage() {
echo "Usage: $0 -h [database host] -d [test database name]"
exit 1
}

while getopts “:h:d:” opt; do
case ${opt} in
h)
db_host=$OPTARG
;;
d)
test_db=$OPTARG
;;
\?)
echo "Invalid option: -$OPTARG" 1>&2
usage
exit 1
;;
:)
echo “Option -$OPTARG requires an argument.” 1>$2
usage
exit 1
;;
esac
done
shift $((OPTIND-1))

if [ -z $db_host ] || [ -z $test_db ]; then
usage
else
echo "Your host is $db_host and your test database is $test_db."
fi

示例程序输出:

./opt.sh: illegal option -- A
Invalid option: -
Usage: ./opt.sh -h [database host] -d [test database name]

所以,基本上有两个问题:

1) 我想完全摆脱第一条错误消息。我想提供我自己的错误信息。2) 为什么我的脚本不生成“无效选项:-A”而不仅仅是“无效选项:-”

最佳答案

您在 getopts 的选项参数周围使用了错误类型的引号,它们是“弯引号”而不是 ASCII 双引号。因此,: 不是选项的第一个字符,因此您不会收到静默错误报告。

改成

while getopts ':h:d:' opt; do

关于linux - getopts 没有将我的选项发送到标准输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37649488/

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