假设编译好的可执行文件名为test, test有3个有效参数-n, -b, -t, 其中-n, -t后不接参数, -b后一定要接参数, -o后接可选参数.
# ./test -x -y -z <------ 无效参数, 会打印错误信息, 并返回字符'?'
输出:
./getopt: invalid option -- 'x'
opt = ?, optarg = (null), optind = 2, argv[2] = -y
./getopt: invalid option -- 'y'
opt = ?, optarg = (null), optind = 3, argv[3] = -z
./getopt: invalid option -- 'z'
opt = ?, optarg = (null), optind = 4, argv[4] = (null)
# ./test -n -b xzz -t
opt = n, optarg = (null), optind = 2, argv[2] = -b
opt = b, optarg = xzz, optind = 4, argv[4] = -t <----------- optarg 指向选项元素的参数, 并且optind跳过了该参数, 直接指向了-t参数
opt = t, optarg = (null), optind = 5, argv[5] = (null)
# ./test -n -bxzz -t <------------- 也可将选项参数与其接的参数写在一起
opt = n, optarg = (null), optind = 2, argv[2] = -bxzz
opt = b, optarg = xzz, optind = 3, argv[3] = -t <----------- optind 同样将指向下一个参数-t
opt = t, optarg = (null), optind = 4, argv[4] = (null)
# ./test -b -t
opt = b, optarg = -t, optind = 3, argv[3] = (null) <----------- 将-t当成了选项元素-b的参数, 之后就不再解析-t, optind为3
# ./test -t -b <---- -b缺少参数
opt = t, optarg = (null), optind = 2, argv[2] = -b
./getopt: option requires an argument -- 'b'
opt = ?, optarg = (null), optind = 3, argv[3] = (null)
# ./test -t a -b xzz <------- 命令行中有一个无用参数 a, 解析时被忽略了, 因为-t不需要接参数
opt = t, optarg = (null), optind = 2, argv[2] = a
opt = b, optarg = xzz, optind = 5, argv[5] = (null)
# ./test -ntb xzz <--------- 还可以把参数连在一起写
opt = n, optarg = (null), optind = 1, argv[1] = -ntb
opt = t, optarg = (null), optind = 1, argv[1] = -ntb
opt = b, optarg = xzz, optind = 3, argv[3] = (null)
# ./test -t -o -b xzz <----- -o选项不接参数
opt = t, optarg = (null), optind = 2, argv[2] = -o
opt = o, optarg = (null), optind = 3, argv[3] = -b
opt = b, optarg = xzz, optind = 5, argv[5] = (null)
# ./test -t -o 10 -b xzz <------ -o选项接参数10
opt = t, optarg = (null), optind = 2, argv[2] = -o
opt = o, optarg = (null), optind = 3, argv[3] = 10 <------------------ <strong><span>可以看到10并没有保存在optarg中</span></strong>
opt = b, optarg = xzz, optind = 6, argv[6] = (null) <----------------- 而-b的参数则保存在optarg中了