How can one change the timestamp of an old commit in Git?

后端 未结 21 2697
慢半拍i
慢半拍i 2020-11-22 08:36

The answers to How to modify existing, unpushed commits? describe a way to amend previous commit messages that haven\'t yet been pushed upstream. The new messages inherit t

21条回答
  •  无人共我
    2020-11-22 08:54

    There are already many great answers, but when I want to change date for multiple commits in one day or in one month, I don't find a proper answer. So I create a new script for this with explaintion, hope it will help someone:

    #!/bin/bash
    
    # change GIT_AUTHOR_DATE for commit at Thu Sep 14 13:39:41 2017 +0800
    # you can change the data_match to change all commits at any date, one day or one month
    # you can also do the same for GIT_COMMITTER_DATE
    
    git filter-branch --force --env-filter '
    
    date_match="^Thu, 14 Sep 2017 13+"              
    
    # GIT_AUTHOR_DATE will be @1505367581 +0800, Git internal format 
    author_data=$GIT_AUTHOR_DATE;                   
    author_data=${author_data#@}                  
    author_data=${author_data% +0800}                # author_data is 1505367581     
    
    oneday=$((24*60*60))
    
    # author_data_str will be "Thu, 14 Sep 2017 13:39:41 +0800", RFC2822 format
    author_data_str=`date -R -d @$author_data`      
    
    if [[ $author_data_str =~ $date_match ]];
    then
        # remove one day from author_data
        new_data_sec=$(($author_data-$oneday))
        # change to git internal format based on new_data_sec
        new_data="@$new_data_sec +0800"             
        export GIT_AUTHOR_DATE="$new_data"
    fi
    ' --tag-name-filter cat -- --branches --tags
    

    The date will be changed:

    AuthorDate: Wed Sep 13 13:39:41 2017 +0800
    

提交回复
热议问题