如何检查 bash 脚本的参数是否为 "flags"

How to check that the argument to a bash script are "flags"

我想确保给定的参数是标志,我的意思是 -x 其中 x 是一些字符或序列。

我已尝试使用以下方法做到这一点:

if [[ "$(echo '' | sed 's/[^-]//g')" -ne "-" ]];
then
  echo "$usage"
  exit
fi

我的理由是,如果在其他字符被剥离时 - 不存在,则它不是标志。

虽然这不起作用,而且显然很脆弱,但我不知道如何正确地做到这一点。

# valid
script.sh -asdf
# invalid
script.sh sdf

您可以这样做以确保 </code> 以 <code>-:

开头
if [[ "${1?}" != -* ]]; then
   echo "$usage"
   exit 1
fi
如果 </code> 不可用,<p><code>${1?} 将使脚本失败。