如何解析Shell脚本输入参数,设置默认与校验格式
【摘要】 本文主要介绍了如何解析Shell脚本输入参数,以IP地址,端口,以及文件和枚举类型演示如何设置默认,并进行格式校验。
本文主要介绍了如何解析Shell脚本输入参数,以IP地址,端口,以及文件和枚举类型演示如何设置默认,并进行格式校验。
#!/bin/bash
###########################################################
#
# Start AI Model Inference Service
#
# Usage: ./run_server.sh [options]
#
###########################################################
# Root directory
ROOTDIR=`pwd`
FILE="model.bin"
IP=`/sbin/ifconfig | grep -w "inet" | awk '{print $2}' | awk 'NR==1{print}'`
PORT="9662"
TYPE="char"
# print usage information
print_usage()
{
echo
echo "Usage: ./run_server.sh [OPTIONS]"
echo
echo "where OPTIONS are:"
echo " -h,--help.....................: print the usage"
echo " -i,--ip.......................: set the server ip (192.168.98.160)"
echo " -p,--port.....................: set the server port (0-65535)"
echo " -f,--file.....................: set the model file (model.bin)"
echo " -t,--type.....................: set the model type (char/word)"
echo
echo "such as ./run_server.sh -i 192.168.98.160 -p 9662 -f model.bin -t char"
echo
}
parse_option()
{
TEMPIP=$IP
stat=1
if [[ $TEMPIP =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
OIFS=$IFS
IFS='.'
TEMPIP=($TEMPIP)
IFS=$OIFS
[[ ${TEMPIP[0]} -le 255 && ${TEMPIP[1]} -le 255 \
&& ${TEMPIP[2]} -le 255 && ${TEMPIP[3]} -le 255 ]]
stat=$?
fi
if [ $stat -eq "1" ]; then
echo -e "Caution :\nThe string "$IP" is not a valid ip address!"
print_usage
exit 1;
fi
if [[ $PORT -lt "0" || $PORT -gt "65535" ]]; then
echo -e "Caution :\nThe string "$PORT" is not a valid port number!"
print_usage
exit 1;
fi
if [ ! -f $FILE ];then
echo -e "Caution :\nThe string "$FILE" is not a valid model file!"
print_usage
exit 1;
fi
if [[ $TYPE != "char" && $TYPE != "word" ]]; then
echo -e "Caution :\nThe string "$TYPE" is not a valid model type!"
print_usage
exit 1;
fi
}
# run server
run_server()
{
parse_option
echo
echo ===================== Run Server ================================
echo
echo Model file ..............: $FILE
echo Server address......: $IP":"$PORT
echo Model type............: $TYPE
echo
echo =============================================================
./bin/start-server --server=$IP --port=$PORT --model=$FILE --type=$TYPE
}
# Options followed by a colon indicate they have a required argument.
if ! options=$(getopt -u -o hi:p:f:t: -l help,ip,port,file,type: -- "$@"); then
exit 1
fi
set -- $options
while [ $# -gt 0 ]
do
case $1 in
-h|--help) print_usage; exit;;
# For options with required arguments, an additional shift is needed.
-i|--ip) IP="$2" ; shift;;
-p|--port) PORT="$2" ; shift;;
-f|--file) FILE="$2" ; shift;;
-t|--type) TYPE="$2" ; shift;;
(--) shift; break;;
(-*) echo "$0: invalid option $1" 1>&2; exit 1;;
(*) break;;
esac
shift
done
run_server
if [ $? -eq 0 ]; then
exit 0;
else
exit 1;
fi
exit 0;
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)