如何检测 getopts 传递的选项不足

如何检测 getopts 传递的选项不足

我想添加一行代码,告诉用户没有给出足够的参数(可能是某处的错误消息。但我不确定在哪里?)

blastfile=
comparefile=
referencegenome=
referenceCDS=

help='''
  USAGE:   sh lincRNA_pipeline.sh
    -c   </path/to/cuffcompare_output file>
    -g   </path/to/reference genome file>
    -r   </path/to/reference CDS file>
    -b   </path/to/RNA file>
'''

while getopts ":b:c:g:hr:" opt; do
  case $opt in
    b)
      blastfile=$OPTARG
      ;;
    c)
      comparefile=$OPTARG
      ;;
    h)
      printf "$help"
      exit 1
      ;;
    g)
      referencegenome=$OPTARG
      ;;
    r)
     referenceCDS=$OPTARG
      ;;
    \?)
      echo "Invalid option: -$OPTARG" >&2
      exit 1
      ;;
    :)
      echo "Option -$OPTARG requires an argument." >&2
      exit 1
      ;;
  esac
done

答案1

一种方法是在getopts解析选项时对选项进行计数。然后,如果传递的数量少于给定数量,则可以退出:

#!/usr/bin/env bash
blastfile=
comparefile=
referencegenome=
referenceCDS=

help='''
  USAGE:   sh lincRNA_pipeline.sh
    -c   </path/to/cuffcompare_output file>
    -g   </path/to/reference genome file>
    -r   </path/to/reference CDS file>
    -b   </path/to/RNA file>
'''

while getopts ":b:c:g:hr:" opt; do
    ## Count the opts
    let optnum++
    case $opt in
        b)
            blastfile=$OPTARG
            echo "$blastfile"
            ;;
        c)
            comparefile=$OPTARG
            ;;
        h)
            printf "$help"
            exit 1
            ;;
        g)
            referencegenome=$OPTARG
            ;;
        r)
            referenceCDS=$OPTARG
            ;;
        \?)
            echo "Invalid option: -$OPTARG" >&2
            exit 1
            ;;
        :)
            echo "Option -$OPTARG requires an argument." >&2
            exit 1
            ;;
    esac
done

[[ $opts -lt 3 ]] && echo "At least 3 parameters must be given"

相关内容