bash - 如何在 bash 中使用 getopts 的示例

标签 bash shell getopts

我想这样调用myscript文件:

$ ./myscript -s 45 -p any_string

$ ./myscript -h  #should display help
$ ./myscript     #should display help

我的要求是:

  • getopt 获取输入参数
  • 检查-s是否存在,如果不存在则返回错误
  • 检查 -s 之后的值是 45 还是 90
  • 检查-p是否存在并且后面有输入字符串
  • 如果用户输入 ./myscript -h 或只是 ./myscript 然后显示帮助

到目前为止我试过这段代码:

#!/bin/bash
while getopts "h:s:" arg; do
  case $arg in
    h)
      echo "usage" 
      ;;
    s)
      strength=$OPTARG
      echo $strength
      ;;
  esac
done

但是使用该代码我会出错。如何使用 Bash 和 getopt 做到这一点?

最佳答案

#!/bin/bash

usage() { echo "Usage: $0 [-s <45|90>] [-p <string>]" 1>&2; exit 1; }

while getopts ":s:p:" o; do
    case "${o}" in
        s)
            s=${OPTARG}
            ((s == 45 || s == 90)) || usage
            ;;
        p)
            p=${OPTARG}
            ;;
        *)
            usage
            ;;
    esac
done
shift $((OPTIND-1))

if [ -z "${s}" ] || [ -z "${p}" ]; then
    usage
fi

echo "s = ${s}"
echo "p = ${p}"

运行示例:

$ ./myscript.sh
Usage: ./myscript.sh [-s <45|90>] [-p <string>]

$ ./myscript.sh -h
Usage: ./myscript.sh [-s <45|90>] [-p <string>]

$ ./myscript.sh -s "" -p ""
Usage: ./myscript.sh [-s <45|90>] [-p <string>]

$ ./myscript.sh -s 10 -p foo
Usage: ./myscript.sh [-s <45|90>] [-p <string>]

$ ./myscript.sh -s 45 -p foo
s = 45
p = foo

$ ./myscript.sh -s 90 -p bar
s = 90
p = bar

关于bash - 如何在 bash 中使用 getopts 的示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16483119/

相关文章:

java - stat 返回 `No such file or directory` ,在 java exec 下运行

c - 在 C 中执行使用 fgets 输入的字符串作为 shell 命令

linux - 对于文件的每一行,grep 一个特定的字符串并进行字符串替换

linux - 带有所有可选参数的 getopts

bash - 大量参数(操作数)在命令行参数传递中排在首位

linux - BASH getopts 可选参数

linux - bash 输出 gulp watch 到多个文件,然后用 tail -f 显示输出

linux - 如何使用命令检查 Linux 中进程的 I/O 利用率

regex - AWK 不同行开始的不同验证

testing - Gnu Makefile,编译应该失败