shell脚本代码片断:参数个数、当前目录、日期格式
参数个数
判断输入的参数个数是否正确:
if [ $# != 3 ]; then echo all params size is $# echo "USAGE: $0 param1 param2 param3" exit 1; fi
如果未输入参数,使用默认,如果输入了参数,则使用参数:
# tradeday默认为当前日期 tradeday=$(date +%Y%m%d) # 如果用户输入了参数,则重置tradeday为输入的参数 if (($# == 1)) then tradeday=$1 fi echo "param size: $#, tradeday: ${tradeday}"
定位到程序所在目录
在cron定时任务中执行程序时,常常cd到程序目录再执行命令:
# 以下三种方式等价,得到执行脚本命令的目录。不管脚本位于哪个位置,总是得到当前目录 dir="`pwd`" dir="$PWD" dir="$(pwd)" # 获取要执行的脚本所有的目录。不管在哪个位置执行脚本,总是得到脚本存储的路径 dir="$( cd "$( dirname "$0" )" && pwd )" cd ${dir}
获取日期格式
在shell中获取当前日期和时间:
currentDate=`date` # output maybe: Mon Mar 25 14:40:32 IST 2021 currentDate=`date +"%D %T"` # 05/10/22 14:28:58 currentDate=`date +%s` # 1652164138 currentDate=`date +"%Y-%m-%d %H:%M:%S"` # 2022-05-10 14:28:58 # 使用 date --help 获取更详细参数介绍