【问题标题】:Convert string to date and perform date comparison in shell script将字符串转换为日期并在 shell 脚本中执行日期比较
【发布时间】:2019-03-01 16:40:46
【问题描述】:

我是 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

【问题讨论】:

标签: git shell


【解决方案1】:

-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

【讨论】:

    猜你喜欢
    • 2011-12-18
    • 1970-01-01
    • 1970-01-01
    • 2014-05-25
    • 2015-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多