Shell 处理时间

场景1:打印时间

now_time=`date +"%Y-%m-%d %H:%M:%S"`
echo $now_time
# 使用双引号可以解析变量,单引号不行
echo 'time is $now_time'
echo "time is $now_time"
x=10
echo 'x is $x'
echo "x is $x"

场景2:计算时间差值

# 获取当前时间的时间戳(秒)
time1=$(date +%s)
sleep 3
time2=$(date +%s)
# 计算时间差(秒)
diff_time=$((time2 - time1))
echo "diff time is $diff_time second"

使用场景1:在k8s中,业务容器定时更新读写层某个文件保存的时间,kubelet定时通过健康检查脚本从该文件中读取时间后计算与当前时间差值,差值在规定时间内则返回0,否则返回1,从而判断业务容器是否存活。

场景3:时间字符串转换成时间戳

time_str="Wed Jul 30 15:30:00 2023"
timestamp=$(date -d "$time_str" +%s)
echo "timestamp is $timestamp seconds"

time_str="2023-07-30 15:30:00"
timestamp=$(date -d "$time_str" +%s)
echo "timestamp is $timestamp seconds"

posted on 2024-07-26 07:53  王景迁  阅读(18)  评论(0编辑  收藏  举报

导航