【问题标题】:How to use getopts in bash script? [duplicate]如何在 bash 脚本中使用 getopts? [复制]
【发布时间】:2018-02-03 23:22:24
【问题描述】:

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

#!/bin/bash

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

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

【问题讨论】:

标签: bash getopts


【解决方案1】:

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

以下代码 sn-ps 显示了如何检查强制参数。

# 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

【讨论】: