【问题标题】:bash getopts validate optionsbash getopts 验证选项
【发布时间】:2015-07-16 23:49:24
【问题描述】:

我在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 字符串中选项标志后面的:getopts 表示“需要参数”。 (字符串开头的: 完全是另外一回事。)

标签: linux bash scripting command-line-arguments getopts


【解决方案1】:

getopts 的参数中的选项后面的: 表示它接受一个参数。由于-l 不需要选项,您应该改用

getopts getopts ":b:r:l"

【讨论】:

  • 天啊!!!这很简单...我在想: 需要分隔选项...谢谢您的帮助
  • 那么如果你有 2 个有和 2 个没有会发生什么? `":b:r:l:x" ? x 前面需要冒号,但这意味着我后面会有冒号.....所以我很困惑
猜你喜欢
  • 2021-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-17
  • 2017-03-06
  • 2014-11-15
  • 2012-08-14
相关资源
最近更新 更多