我必须用一个Unix脚本来传递参数:在UNIX上使用getopt的外壳
./Script.sh -c "abc" -d "def" -k "abc -d -c"
其中用于参数:
-c
= “ABC”-d
= “高清”-k
=“abc -d -c”
如何处理Uunix shell脚本中的选项?
我必须用一个Unix脚本来传递参数:在UNIX上使用getopt的外壳
./Script.sh -c "abc" -d "def" -k "abc -d -c"
其中用于参数:
-c
= “ABC”-d
= “高清”-k
=“abc -d -c”如何处理Uunix shell脚本中的选项?
有一个命令getopts
和一个程序getopt
,但我认为,当你需要处理参数时,你已经超出了shell脚本。
我真的不确定getopts
是如何工作的,从来没有真正使用它;但here,并检查你的shell的文档。
getopt
将您的参数分解为标志 - 根据我所知可以休息。
使用'getopt'在参数中容易出现空格问题 - 基本上,它不能准确处理它们。内置的'getopts'确实可以正确处理参数中的空格。 – 2010-09-27 02:27:50
下面是一些选项使用getopts
处理:
# -F Final version (do not append date to version)
# -s suffix Add '-suffix' after version number
# -V Print version and exit
# -h Print help and exit
# -j jdcfile JDC file for project - required
# -q Quiet operation
# -v Verbose operation
arg0=$(basename $0 .sh)
usage()
{
echo "Usage: $arg0 [-hqvFV] [-s suffix] -j jdcfile file.msd" 1>&2
exit 1
}
error()
{
echo "$0: $*" 1>&2
exit 1
}
Fflag=
suffix=
jdcfile=
qflag=
vflag=no
while getopts FVhj:qs:v opt
do
case "$opt" in
(F) Fflag="-F";;
(V) echo "Version information";;
(h) echo "Help information";;
(j) jdcfile="$OPTARG";;
(q) qflag="-q";;
(s) suffix="$OPTARG";;
(v) vflag=yes;;
(*) usage;;
esac
done
shift $(($OPTIND - 1))
case $# in
(1) : OK;;
(*) usage;;
esac
if [ -z "$jdcfile" ]
then error "you did not specify which jdcfile to use (-j option)"
fi
脚本然后继续并执行基于它被赋予了选择它的任务。 shift
删除'消费'选项,只留下文件名参数。
#!/ bin/bash args ='getopt c:m:p $ *'if if [$? != 0 -o $#== 0] then echo'Usage:-c
参数可以包含空格,所以要么使用getopts
内置shell命令,要么使用GNU增强版的外部getopt
程序。
getopts
选项更便携,因为并非所有系统都具有GNU增强版本getopt
。例如,Linux具有GNU增强版本,但Mac OS X不支持。原始版本getopt
不支持空格。尽管存在这种限制,但您可能想要使用GNU增强版本的原因有很多:它支持长期选项名称,其中getopts
不支持。
这是如何使用GNU增强getopt
与空格。使用"[email protected]"
(使用$ @而不是$ *并确保双引号在其周围)以及eval
整个set
命令很重要,以便正确处理空格。
eval set -- `getopt --long currdir:,dir:,argval:,verbose -o c:d:k:v -- "[email protected]"`
while [ $# -gt 0 ]
do
case "$1" in
-c | --currdir) CURRDIR="$2"; shift;;
-d | --dir) MYDIR="$2"; shift;;
-k | --argval) ARGVAL="$2"; shift;;
-v | --verbose) VERBOSE=yes;;
esac
shift
done
当您尝试'getopt -T; echo $?'? – 2010-09-27 03:40:15