系统相关
首页 > 系统相关> > 必需的选项getopts linux

必需的选项getopts linux

作者:互联网

我必须编写一个bash脚本:

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

h和c是可选选项.我是必需的,当运行脚本时,如果它没有i选项 – >错误信息.

如何在getopts中创建一个必需的选项?
谢谢!

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

解决方法:

您无法进行必需的参数,因为“如果缺少该参数,则内置的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

标签:getopts,bash,linux
来源: https://codeday.me/bug/20190830/1768031.html