linux - 当没有输入参数时,如何使用 getopts 来避免运行脚本?

标签 linux bash shell unix scripting

这是我正在尝试做的

while getopts "h?rd" opt; do
    case "$opt" in
    h|\?)
        echo "invalid"
        exit 0
        ;;
    r)  report=1
        ;;
    d)  delete=1
        ;;
    esac
done

-r & -d 起作用,作为参数传递的任何其他字符也会发出错误。 但如果我不使用参数,代码也会运行。我也想提示错误。我怎样才能做到这一点?

最佳答案

您可以使用 bash 的 $# 变量来查找任何参数。也可以通过在 getopts

中使用 case *) 获取其他无效参数
#!/bin/bash

if [ $# -lt 1 ]; then
  echo "no arguments"
  exit 1
fi
while getopts ":h\?rd" opt; do
    case "$opt" in
    h|"\?")
        echo "valid"
        exit 0
        ;;
    r)  report=1
        ;;
    d)  delete=1
        ;;
    *)  echo "not valid"
        ;;
    esac
done

关于linux - 当没有输入参数时,如何使用 getopts 来避免运行脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38309991/

相关文章:

linux - 无法使用带有文件描述符的群来锁定文件

linux - 需要 bash 中选项卡的脚本解决方案

linux - Java操作系统

复制程序: File Permission Denied

linux - 从三列文件中删除重复记录

Bash 脚本,数组未按预期创建

linux - 如何在我的 Linux 机器上找到主 IP 地址?

string - Bash 脚本捕获输出到终端

linux - Expect 脚本中的 Spawn 无法访问环境变量

java - java程序中如何向shell脚本传递参数