如何在 bash 脚本中使用 getopts?

How to use getopts in bash script?

我正在尝试像这样使用 getopts:

#!/bin/bash

while getopts "i" option
do
 case "${option}"
 in
 i) INT=${OPTARG};;
 esac
done
echo "$INT"

但只有当我使用 getopts "i:" 时它才会打印 $INT。如果我理解正确的话,optstring 中的冒号意味着相应标志需要值。但我想让这个标志成为可选的。 谁能解释为什么脚本会这样,我该如何解决?

你不能让它 (bash getopts) 那样可选。 “getopts”不支持强制或可选选项。 您需要为此编写代码。 如果指定了“:”,则该选项需要有一个参数。没有办法绕过它。

以下代码片段显示了如何检查强制参数。

# Mandatory options
arg1=false;
..
...
case "${option}"
 in
 i) INT=${OPTARG}; arg1=true;
 ;;
 esac
 if  ! $arg1;
 then
  echo -e "Mandatory arguments missing";
  # assuming usage is defined
  echo -e ${usage};
  exit 1;
fi