【发布时间】:2015-01-03 19:23:22
【问题描述】:
系统:freebsd 9.2
我想使用 getopts 来解析命令行。比如
./tesh.sh -o good a.c
can get good.out
./tesh.sh -o a.c
can get a.out
但在 getopts 中没有“选项”变量。 有谁知道如何解决这个问题? 找了很多网页,没有人能解决。
这是我的代码
#!/bin/bash
while getopts "hs:o:" optname
do
case "$optname" in
"h")
echo "Option $optname is specified"
;;
"s")
echo "Option $optname has value $OPTARG"
;;
"o")
echo "$optname"
;;
"?")
echo "Unknown option $OPTARG"
;;
":")
;;
*)
# Should not occur
echo "Unknown error while processing options"
;;
esac
echo "OPTIND is now $OPTIND"
done
如果我输入 ./test.sh -o a.c 它将打印 echo "$optname"
我想要那个 如果我输入 ./test.sh -o 也可以打印 echo "$optname"
现在它会打印错误信息
谢谢!
【问题讨论】:
-
详细说明您的方案,因为您的要求并不清楚和混淆。
-
见Shell script templates;答案的一部分概述了如何使用
getopts解析命令行。您也可以在Usinggetoptsin Bash shell script to get long and short command line options 中找到有用的信息。 -
@SriharshaKalluru 谢谢!我添加了更多关于我的问题
-
@JonathanLeffler 谢谢!但我可以找到我想要的解决方案 =(
-
如果您定义需要参数的“-o”选项并且您没有提供参数,则会收到错误消息。