简体   繁体   中英

bash getopts validate options

I have following code in bash script:

# 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))

Question:

if use option -b it required inputfile but -l it just need to print list of directories without passing any argument, is there any simple way to find out which option need 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

if i pass any argument it works

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

The : following an option in the argument to getopts indicates that it takes an argument. Since -l doesn't require an option, you should instead use

getopts getopts ":b:r:l"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM