Git commit message from a text file

Once I need to do many commits and in each commit I have prepared the commit message. It’s very sensible to do this automatically since everything is already set. But wait, does Git provide a way to make it read a commit message from a text file?

After reading the manual page, yes `git help commit`, I could not find any clue on how to do this. Git provides `-m` option to enter the message inline, but I found this to be very limited since I have a paragraph long message. Git also provides `-t` to specify a template file. This is very close to what I need, however I still need to save and close the text editor which still pops up. Nah, I could not automate with this.

Then I realized that I can trick Git by changing the text editor it uses when asking user for the message. We can change the editor by setting the `EDITOR` environment variable. Git will call whatever specified there and give another parameter: the file Git will read for commit message. By default it will be set to `.git/COMMIT_EDITMSG`

So, for example, if I enter `/usr/bin/gedit` to `EDITOR`, Git will execute the following

/usr/bin/gedit .git/COMMIT_EDITMSG

Gedit application will run and Git wait until it closes. Then used whatever written in `.git/COMMIT_EDITMSG` as the commit message. We can also give parameter to Gedit, like adding `–new-window`, that will tell Gedit to open a new window instead of just using what is already opened.

$ EDITOR=”/usr/bin/gedit –new-window” git commit

That said, to make Git read a text file and use it as commit message, we can do a magic by using `cp`! Yes, the one that can create a copy! Let me show you how..

What will Git do if we set the `EDITOR` variable like the following?

$ EDITOR=”cp a-text-file.txt” git commit

Yes, Git will execute `cp a-text-file.txt .git/COMMIT_EDITMSG`, then wait until the execution finishes, and finally use the content of `.git/COMMIT_EDITMSG` as the commit message. In other words, we use what is written in `a-text-file.txt` as the commit message without touching any text editor! Perfect!

PS: This should be also applicable for other applications that use similar method of asking an input.

2 thoughts on “Git commit message from a text file”

Leave a Reply