数字类型字符串转数字的方法
字符串转换成数字有方法:
-
$[]
-
$(())
-
expr
-
let
举例
shell里面怎么样把字符串转换为数字?
例如:a=“024”
-
用${{a}}
-
用let达到(()) 运算效果。
let num=0123;
echo $num;
83
3,双括号运算符:
a=$((1+2));
echo $a;
等同于:
a=`expr 1 + 2`
应用代码
日期"20210107’字符串需要先截取年月日,然后获取数字,如"07" —>7。
使用 $[] 命令
# RUN_BATCH_DATE_TYPE: M: monthly(Run once a month) W:weekly (Obtain results: 0 for Sunday, 1-6 for Monday to Saturday) D:day (Every day) default day type
# RUN_BATCH_DATE: Specific batch running date .This field must be used with RUN_BATCH_DATE_TYPE default : RUN_BATCH_DATE=1
RUN_BATCH_DATE_TYPE="D"
RUN_BATCH_DATE=1
# Gets the day of the week for current system time
# WEEK_DAY=`date -d "" +%w`
# MONTH_DAY=`date -d "" +%d`
WEEK_DAY=`date -d "$end_date" +%w`
MONTH_DAY=`date -d "$end_date" +%d`
if [ $RUN_BATCH_DATE_TYPE == "D" ]; then
echo "The run batch type is ${RUN_BATCH_DATE_TYPE} : Day"
elif [ $RUN_BATCH_DATE_TYPE == "W" ] && [ $[RUN_BATCH_DATE] == $[WEEK_DAY] ] ; then
echo "The run batch type is ${RUN_BATCH_DATE_TYPE} : weekly ,The running time is weekly : ${RUN_BATCH_DATE}"
elif [ $RUN_BATCH_DATE_TYPE == "M" ] && [ $[RUN_BATCH_DATE] == $[MONTH_DAY] ] ; then
echo "The run batch type is ${RUN_BATCH_DATE_TYPE} : monthly ,The running time is monthly : ${RUN_BATCH_DATE}"
else
# exit 0
echo "No ${RUN_BATCH_DATE_TYPE} ${RUN_BATCH_DATE} "
fi
特别说明
$[]
在转换数字的时候,在不同的linux 环境,有时候失效。推荐使用 $(())
使用 $(()) 命令
if [ $Run_Batch_Date_Type == "D" ]; then
echo "The run batch type is ${Run_Batch_Date} : Day"
elif [ $Run_Batch_Date_Type == "W" ] && [ $((Run_Batch_Date)) == $((WEEK_DAY)) ] ; then
echo "The run batch type is ${Run_Batch_Date} : weekly ,The running time is weekly : ${Run_Batch_Date}"
elif [ $Run_Batch_Date_Type == "M" ] && [ $((Run_Batch_Date)) == $((MONTH_DAY)) ] ; then
echo "The run batch type is ${RUN_BATCH_DATE_TYPE} : monthly ,The running time is monthly : ${Run_Batch_Date}"
else
echo "Not at script run time. Run_Batch_Date_Type= ${Run_Batch_Date_Type} Run_Batch_Date=${Run_Batch_Date},but WEEK_DAY= $WEEK_DAY ,MONTH_DAY= $MONTH_DAY"
exit 0
fi
exit 命令说明
exit 命令可以接受一个整数值作为参数,代表退出状态。如果不指定,默认状态值是 0。使用$?
可以接收这个退出状态
退出状态为 0 表示成功,退出状态为非 0 表示执行失败(出错)。
注意:exit 退出状态只能是一个介于 0~255 之间的整数,其中只有 0 表示成功,其它值都表示失败。