linux - bash getopts 验证选项

标签 linux bash scripting command-line-arguments getopts

我在 bash 脚本中有以下代码:

# argument validation and usage help
usage()
{
cat << EOF
usage: $0 options

File Integrity Monitoring Script:

OPTIONS:
   -b      input file for [backup]
   -r      input file for [diff report]
   -l      list backup files
EOF
}

if [ $# -eq 0 ]
  then
    usage
    exit 0
fi


while getopts ":b:r:l:" o; do
    case "${o}" in
        b)
            B=${OPTARG}
            backup $B
            ;;
        r)
            R=${OPTARG}
            diffcheck $R
            ;;
        l)
            ls -ld /root/backup/* | awk -F/ '{print $(NF)}'
            ;;
        *)
            usage
            exit 0
            ;;
    esac
done
shift $((OPTIND-1))

问题:

如果使用选项 -b 它需要 inputfile 但是 -l 它只需要打印目录列表而不传递任何参数,是吗有什么简单的方法可以找出哪个选项需要 argument 吗?

spatel # ./final.sh -l
usage: ./final.sh options

File Integrity Monitoring Script:

OPTIONS:
   -b      input file for [backup]
   -r      input file for [diff report]
   -l      list backup files

如果我传递任何它有效的参数

spatel # ./final.sh -l xxx
May-06-15-10-03
May-06-15-10-04
May-06-15-10-19
May-06-15-11-30

最佳答案

: 跟在 getopts 的参数中的一个选项之后表示它接受一个参数。由于 -l 不需要选项,因此您应该使用

getopts getopts ":b:r:l"

关于linux - bash getopts 验证选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30083560/

相关文章:

Linux 性能 : is it possible to somehow ignore busy waiting threads?

linux - 不可见的终端输出正在破坏脚本

linux - 如何使 .bashrc 中的更改在当前终端中生效

regex - 负向后看中的 grep 反斜杠

regex - 为什么 "script"命令会生成 ^[ 和 ^M 字符以及如何使用 vim 搜索和替换将它们删除?

python - 如何在python3.6中导入python3 lib

linux - 如何在变量中搜索特定的一段文本?

Python-brisa 可在 Eclipse 中运行,但不能在 shell 中运行

c++ - QML错误: qrc:/Main. qml:24模块 "system"未安装

linux - 删除 zsh 后 shell 中的 Ubuntu 服务器登录循环