Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在bash脚本中使用getopts?_Bash_Getopts - Fatal编程技术网

如何在bash脚本中使用getopts?

如何在bash脚本中使用getopts?,bash,getopts,Bash,Getopts,我正在尝试像这样使用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:

#!/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

冒号表示需要一个选项参数。没有冒号意味着根本不需要选项参数。上的Bash手册不支持可选参数。为此,您需要GNU
getopt
(具有许多不同的语义)。@JonathanLeffler啊,非常感谢。我想我需要删除我的问题,因为它无法回答。请参阅相关问题。它不是直接复制的,但包含有用的信息。有一个扩展的
getopt
命令版本可从中获得。