如何使用 getopts 正确解析 shell 脚本标志和参数

St3*_*3an 2 shell bash options getopts arguments

我正在使用这个:

例如 ./imgSorter.sh -d directory -f format

脚本的内容是:

#!/bin/bash
while getopts ":d:f:" opt; do
  case $opt in
    d)
      echo "-d was triggered with $OPTARG" >&2
      ;;
    f)
      echo "-f was triggered with $OPTARG" >&2
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      exit 1
      ;;
  esac
done
Run Code Online (Sandbox Code Playgroud)

用例 :

$ ./imgSorter.sh -d myDir -d was triggered with myDir 好的

$ ./imgSorter.sh -d -f myFormat -d was triggered with -f NOK:以 - 开头的字符串如何不被检测为标志?

Kus*_*nda 5

您已经告诉getopts-d选项应该带一个参数,并且在您使用的命令行-d -f myformat中明确 (?) 说“-f是我给该-d选项的参数”。

这不是代码中的错误,而是命令行上脚本的使用中的错误。

您的代码需要验证选项参数是否正确以及所有选项是否以适当的方式设置。

可能像

while getopts "d:f:" opt; do
  case $opt in
    d) dir=$OPTARG      ;;
    f) format=$OPTARG   ;;
    *) echo 'error' >&2
       exit 1
  esac
done

# If -d is *required*
if [ ! -d "$dir" ]; then
    echo 'Option -d missing or designates non-directory' >&2
    exit 1
fi

# If -d is *optional*
if [ -n "$dir" ] && [ ! -d "$dir" ]; then
    echo 'Option -d designates non-directory' >&2
    exit 1
fi
Run Code Online (Sandbox Code Playgroud)

如果该-d选项是可选的,并且您想在上面的代码中为变量使用默认值,则dir可以dirwhile循环之前先设置为该默认值。

命令行选项不能同时接受和不接受参数。