如何在 bash 中使用 getopts 的示例 [英] An example of how to use getopts in bash

查看:28
本文介绍了如何在 bash 中使用 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 然后显示帮助
  • getopt here to get the input arguments
  • check that -s exists, if not return an error
  • check that the value after the -s is 45 or 90
  • check that the -p exists and there is an input string after
  • if the user enters ./myscript -h or just ./myscript then display help

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

I tried so far this code:

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

但是使用该代码我会出错.如何使用 Bash 和 getopt 来实现?

But with that code I get errors. How to do it with Bash and 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 中使用 getopts 的示例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆