Swapping two files in git

I found myself wanting to swap the names of two files in my Git repository, and couldn't find an easy way to do it with the git command. So I extended it. Now I just type git swap file1 file2 to rename the two files to each other.

How to do it

I wrote a simple shell script to automate the renaming, and saved it in a file called git-swap in my PATH. Here's the script (also available on GitHub):


TEMP="/tmp/$(basename $0).$$.tmp"

cp $1 $TEMP
git mv -f $2 $1
mv $TEMP $2
git add $2

To use it, just type:

$ git swap file1 file2
warning: destination exists; will overwrite!

Don't worry about the warning; that's just git mv -f letting us know that we're writing one file over the top of another one.

If you check the status you should see that your files have been swapped, and all you need to do is commit:

$ git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
# renamed:    file1 -> file2
# renamed:    file2 -> file1

You can also find the git-swap script on GitHub.

I love feedback and questions — please feel free to get in touch on Mastodon or Twitter, or leave a comment.

Published on in Git