+ -
当前位置:首页 → 问答吧 → 脚本是怎样区分选项和参数的?

脚本是怎样区分选项和参数的?

时间:2011-03-09

来源:互联网

如题了....
比方说我写了个脚本:script 在执行的时候需要添加选项和参数 脚本如下了: 
#!/bin/sh
FILES=””
TRCASE=””
EXT=””
OPT=”no”
error_msg()
{
_FILENAME=$1
echo “`basename $0`:Error the conversion failed on $_FILENAME”
}
if [ $# -eq 0 ]
then
echo “For more info try `basename $0` --help”
exit 1
fi
while [ $#-gt 0 ]
do
case $1 in
-u) TRCASE=upper
EXT=”.UC”
OPT=yes
shift
;;
-l)TRCASE=lower
EXT=”.LC”
OPT=yes
;;
--help) echo “convert a file(s) to upper from lowercase”
echo “convert a file(s) to lowercase to uppercase”
echo “Will convert all characters according to the”
echo “specified command option”
echo “where option is ”
echo “ –l Convert to lowercase ”
echo “ –u convert to uppercase”
echo “The original file(s) is not touched . A new file(s)”
echo “will be created with either a .UC or .LC extension”
echo “usage:$0 -[l|u] file [file …]”
exit 0
;;
-*)echo “usage:`basebame $0` -[l|u] file [file..]”
exit 1
;;
*) if [ -f $1 ]
then
FILES=$FILES” ”$1
else
echo “`basename $0`:Error cannot find the file $1”
fi
shift
;;
esac
done
#no option given …help the user
if[ “OPT” = “no” ];then
echo “`basename $0` :Error you need to specify an option .No action taken”
echo “try `basename` $0 --help”
exit 1
fi
#now read in all the files
#use the variable LOOP,I just love the word LOOP
for LOOP in $FILES
do
case $TRCASE in
lower) cat $LOOP|tr “[a-z]” “[A-Z]” > $LOOP$EXT
if [ $? != 0 ]
then
error_msg $LOOP
else
echo “Converted file called $LOOP$EXT”
fi
;;
upper)cat $LOOP|tr “[A-Z]” “[a-z]” >$LOOP$EXT
if[ $? != 0 ]
then
error_msg $LOOP
else
echo “Converted file called $LOOP$EXT”
fi
;;
esac
done


在error_msg函数中提到了 $1 ,脚本执行需要添加选项 : ./script -[ l | u ] file 这个$1是怎么区分是选项( -l 和-u )还是参数file的阿?

作者: 南极雨   发布时间: 2011-03-09

回复 南极雨


    如果说不用getopt,你自己写的话就得自己在脚本里加判断了

作者: wtuter   发布时间: 2011-03-09