必需选项getopts linux

7

我需要编写一个bash脚本:

    schedsim.sh [-h] [-c #CPUs ] -i pathfile

h和c是可选选项。当运行脚本时,如果没有i选项,则会显示错误消息。

如何在getopts中设置必需的选项? 谢谢!

另一个问题:如何为选项的参数设置默认值?比如,如果没有提供c的参数,则c的参数的默认值为1。

1个回答

7

你不能强制要求参数,例如“如果缺少该参数,则 getopts 内置会返回错误”。

但是,你可以很容易地自己创建一个能够达到此目的的函数:

#!/bin/bash

function parseArguments () {
  local b_hasA=0
  local b_hasB=0
  local b_hasC=0

  while getopts 'a:b::c' opt "$@"; do
    case $opt in
    'a')
      b_hasA=1
      ;;
    'b')
      b_hasB=1
      ;;
    'c')
      b_hasC=1
      ;;
    esac
  done

  if [ $b_hasA -ne 0 ]; then
    echo "A present"
  fi
  if [ $b_hasB -ne 0 ]; then
    echo "B present"
  fi
  if [ $b_hasC -ne 0 ]; then
    echo "C present"
  else
    echo "Error: C absent"
    exit 1
  fi
}

#Quotes required to avoid removing characters in $IFS from arguments
parseArguments "$@"

测试:

$ ./test.bash -c
C present

$ ./test.bash -b
./test.bash: option requires an argument -- b
Error: C absent

$ ./test.bash -b foo
B present
Error: C absent

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接