Get current date and time to commit message to git

5,240

You can use Command Substitution to get the current date and time when your script is run:

git commit -m "$(date +"%D %T")"

Alternatively you could save date's output in a variable, e.g. if you want to capture the time the script was started at, add as the first command e.g.

timestamp=$(date +"%D %T")

and use it later like:

git commit -m "$timestamp: Backup"

If this is really your whole script, remember to add a Shebang as the first line. I always try to avoid cd in scripts and rather give full paths, last but not least it helps to keep the code clean and easily understandable if you store long paths in variables:

#!/bin/bash
path1=/var/www/html/myweb
path2=/home/myweb/backups/myweb

php "$path1/bin/magento" setup:backup --code --media --db
cp "$path1/var/backups/*" "$path2/backups/"
git add "$path2"
git commit -m "$(date +"%D %T")"
git push

Note that you can't use ~ in a path when you do it like that because variables are expanded after the tilde, you can use $HOME though.

Share:
5,240
RUC...
Author by

RUC...

Updated on September 18, 2022

Comments

  • RUC...
    RUC... over 1 year

    I am writing a shell script to auto push the backups in to git using crontab. How can I get the current date and time into the commit message. This is my script:

    cd /var/www/html/myweb
    php bin/magento setup:backup --code --media --db
    cp /var/www/html/myweb/var/backups/* /home/myweb/backups/myweb/backups/
    cd /home/myweb/backups/myweb
    git add .
    git commit -m  "date +"%D %T""
    git push
    
    • Harsh Patel
      Harsh Patel over 6 years
      for branch in git branch -r | grep -v HEAD;do echo -e git show --format="%ci %cr" $branch | head -n 1 \\t$branch; done | sort -r Raw
    • J. Starnes
      J. Starnes over 6 years
      @HarshPatel Can you include an answer with instructions on how and why to do that? Leaving a half-answer as a comment can often cause more harm than good. Thanks.