You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bash脚本IF条件中日期比较失效问题求助

问题排查与修复

你的问题核心是时间顺序判断的代码位置错误:判断开始时间晚于结束时间的if块被放在格式校验的while循环内部,只有当格式输入错误时才会进入循环执行这段判断。如果格式正确但时间顺序反了,while的条件不成立,直接跳出循环,根本不会执行时间判断的逻辑,所以提示语句永远不会触发。

另外,直接用[[ $start_date_time > $end_date_time ]]做字符串比较不可靠——Bash会按字典序比对,虽然部分场景结果巧合正确,但逻辑本质错误。你用时间戳+%s的比对方式是正确的,只是位置没放对。

修复后的脚本

echo "Input start date and time (yyyy-mm-dd hh:mm) :"
read start_date_time
echo "Input end date and time(yyyy-mm-dd hh:mm) :" 
read end_date_time

# 循环条件:格式错误 或者 开始时间晚于结束时间
while true; do
    # 校验格式是否正确
    local start_valid=$(date -d "$start_date_time" +%Y-%m-%d\ %H:%M 2>/dev/null)
    local end_valid=$(date -d "$end_date_time" +%Y-%m-%d\ %H:%M 2>/dev/null)
    
    if [[ "$start_valid" != "$start_date_time" || "$end_valid" != "$end_date_time" ]]; then
        echo "Invalid input! Please reinsert in the correct format (yyyy-mm-dd hh:mm)."
    elif [[ $(date -d "$start_date_time" +%s) -gt $(date -d "$end_date_time" +%s) ]]; then
        echo "Start datetime cannot be greater than end datetime."
    else
        # 格式正确且时间顺序合法,跳出循环
        break
    fi

    # 重新获取输入
    echo "Start date and time :"
    read start_date_time
    echo "End date and time :"
    read end_date_time
done

关键修改点

  • 将循环改为while true,在内部分别判断格式错误、时间顺序错误两种情况,满足任意一种就提示用户并重新获取输入,全部合法才跳出循环。
  • 提前把格式校验结果存入变量,避免重复执行date命令,提升脚本效率。
  • 分离两种错误的提示信息,让用户能清晰知道问题类型。

内容的提问来源于stack exchange,提问作者Luqman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 17:32:38