bash 必需选项 getopts linux

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26316612/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 11:31:43  来源:igfitidea点击:

Required option getopts linux

linuxbashgetopts

提问by rocketmanu

I have to write a bash script:

我必须写一个 bash 脚本:

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

h and c are optional options. i is required, when run script if it doesn't have i option -> error message.

h 和 c 是可选选项。i 是必需的,当运行脚本时,如果它没有 i 选项 -> 错误消息。

How to make a required option in getopts? Thanks!

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

another question: how to make default value for an argument of option? say, if c isn't provided argument -> default value of argument of c is 1.

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

回答by Olivier Diotte

You cannot make an argument required as in "the getopts builtin returns an error if that argument is missing".

您不能像“如果缺少该参数,则 getopts 内置函数会返回错误”那样要求参数。

But it is trivial to make a function that does that yourself:

但是制作一个自己做的函数是微不足道的:

#!/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 "$@"

Tests:

测试:

$ ./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