代码之家  ›  专栏  ›  技术社区  ›  Sri

将字符串转换为日期并在shell脚本中执行日期比较

  •  0
  • Sri  · 技术社区  · 7 年前

    我是shell脚本新手,尝试执行以下操作:

    if [[ $($last_update_date) -ge '2018-09-20' ]]; then
       echo "hello";
    fi
    

    last_updated_date 就像 2018-09-01 . 我需要将它与特定日期进行比较并执行一些git操作。

    有什么帮助吗?

    for branch in $(git branch -r | sed 's/^\s*//'); do 
    
        ## Info about the branches before deleting
        echo branch: $branch;
        hasAct=$(git log --abbrev-commit --pretty=format:"%ad" --date=relative -1 $branch); 
        lastActivity=$(echo "$hasAct" | grep Date: | sed 's/Date: //');
    
        last_updated_date=$(git log --pretty=format:"%ad" --date=short -n 1 $branch);
    
        echo "$last_updated_date";
        echo "$hasAct";
    
        if [[ $($last_update_date) -ge '2018-09-20' ]]; then
           echo "hello";
        fi
        ## Delete from the remote
        ##git push origin --delete $k
    done
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   muru Rider44    7 年前

    -ge 进行数字比较,但日期 2018-09-20 不是数字。但是一个约会 YYYY-MM-DD 格式可以按字典顺序进行比较,因此您可以尝试:

    if [[ $last_update_date > '2018-09-20' ]]; then
       echo "hello";
    fi
    

    或者如果不使用sh而不是bash:

    if [ "$last_update_date" \> '2018-09-20' ]; then
       echo "hello";
    fi