手工处理方式能满足大多数的简单需求,配合shift使用也能构造出强大的功能,但在要处理复杂选项的时候建议用下面的两种方法。 2. getopts/getopt 处理命令行参数是一个相似而又复杂的事情,为此,C提供了getopt/getopt_long等函数, C++的boost提供了Options库,在shell中,处理此事的是getopts和getopt. getopts和getopt功能相...
1. getopts是bash内建命令的, 而getopt是外部命令 2. getopts不支持长选项, 比如: --date 3. 在使用getopt的时候, 每处理完一个位置参数后都需要自己shift来跳到下一个位置, getopts只需要在最后使用shift $(($OPTIND - 1))来跳到parameter的位置。 4. 使用getopt时, 在命令行输入的位置参数是什么, 在ge...
Option index at start: 1"Type: fruit"Option index after 2getoptsinvocations: 3"Name: apple"Option index after 3getoptsinvocations: 5"Color: red"Option index after 4getoptsinvocations: 7 Option index at end: 7 The remaining arguments to be processed: 85Copy 执行shift 命令后,getopts 处理后,$@...
1. getopts是bash内建命令的, 而getopt是外部命令 2. getopts不支持长选项, 比如: --date 3. 在使用getopt的时候, 每处理完一个位置参数后都需要自己shift来跳到下一个位置, getopts只需要在最后使用shift $(($OPTIND - 1))来跳到parameter的位置。 4. 使用getopt时, 在命令行输入的位置参数是什么, 在ge...
) echo "Invalid option: -$OPTARG" 1>&2 exit 1 ;; : ) echo "Invalid option: -$OPTARG requires an argument" 1>&2 exit 1 ;; esac done shift $((OPTIND -1)) echo "Remaining arguments: $@" 遇到的问题及解决方法 问题:getopts 报告无效选项错误。 原因:用户提供了脚本不支持的选项。 解决...
1、bash 内置的getopts: 先看简单的例子: #!/bin/bashwhile getopts 'd:Dm:f:t:' OPT; docase$OPTind)DEL_DAYS="$OPTARG";;D)DEL_ORIGINAL='yes';;f)DIR_FROM="$OPTARG";;m)MAILDIR_NAME="$OPTARG";;t)DIR_TO="$OPTARG";;?)echo"Usage:`basename$0`[options] filename"esacdoneshift$(($OP...
echo "Remaining arguments:" for arg do echo '--> '"\`$arg'" ; done 比如我们使用 ./test -a -b arg arg1 -c 你可以看到,命令行中多了个arg1参数,在经过getopt和set之后,命令行会变为: -a -b arg -c – arg1 $1指向-a,$2指向-b,$3指向arg,$4指向-c,$5指向–,而多出的arg1则被放...
getopts和getopt功能相似但又不完全相同,其中getopt是独立的可执行文件,而getopts是由Bash内置的。 先来看看参数传递的典型用法: * ./test.sh -a -b -c : 短选项,各选项不需参数 * ./test.sh -abc : 短选项,和上一种方法的效果一样,只是将所有的选项写在一起。
在bash中,可以⽤以下三种⽅式来处理命令⾏参数,每种⽅式都有⾃⼰的应⽤场景。* ⼿⼯处理⽅式 * getopts * getopt 下⾯我们依次讨论这三种处理⽅式。1. ⼿⼯处理⽅式 在⼿⼯处理⽅式中,⾸先要知道⼏个变量,还是以上⾯的命令⾏为例:* $0 : ./test.sh,即命令...
Bash: parsing arguments with ‘getopts’ | rsalveti's random thoughts: #!/bin/bash # Argument = -t test -r server -p password -v usage() { cat << EOF usage: $0 options This script run the test1 or test2 over a machine.