while getopts :ab:c: opt; do case $opt in a) echo "option:a, arg:"$OPTARG", index:"$OPTIND;; b) echo "option:b, arg:"$OPTARG", index:"$OPTIND;; c) echo "option:c, arg:"$OPTARG", index:"$OPTIND;; *) echo "Error option, index:"$OPTIND;; esac done echo "End";
shell的输出结果:
1 2 3 4 5 6 7
hostname@hostname ~/W/t/tmp> sh ./opts.sh -a -b banana -s -ccherry option:a, arg:, index:2 option:b, arg:banana, index:4 Error option, index:5 option:c, arg:cherry, index:6 End hostname@hostname ~/W/t/tmp>
while true do case "$1" in -a | --apple) echo "option a" shift;; -b) echo "option b arg $2" shift 2;; --banana) echo "option banana arg $2" shift 2;; -e) echo "option e arg $2" shift 2;; --) shift break;; *) echo "Internal error!" exit 1; esac done
shell输出的结果如下:
1 2 3 4 5 6 7
deranpan@panderan ~/W/t/tmp> sh ./opt-long.sh -a -b b-arg -ee-arg --apple --banana banana option a option b arg b-arg option e arg e-arg option a option banana arg banana deranpan@panderan ~/W/t/tmp>