Does git pull after init remove untracked files

git

I just made a simple script and created a new repository for it on GitHub. After initializing the local repo, moving the script to the repository and pulling the GitHub repository (containing only a README.md file), the script was gone. Is this normal behavior? And is there some way to restore the file?

Here are the commands, as executed:

$ mkgithub ~/dev/cr2meta2jpg
Initialized empty Git repository in /home/username/dev/cr2meta2jpg/.git/
$ mv test.sh ~/dev/cr2meta2jpg/cr2meta2jpg.sh
$ cd ~/dev/cr2meta2jpg/
$ ls
cr2meta2jpg.sh
$ git pull
remote: Counting objects: 3, done.
remote: Compressing objects: 100% (2/2), done.
remote: Total 3 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (3/3), done.
From github.com:l0b0/cr2meta2jpg
 * [new branch]      master     -> origin/master
$ ls
README.md

Best Answer

A git pull will not overwrite local changes unless you use git add before. Even in this case, you can still recover your data.

When you issued git add before the pull:

mkgithub blub
cp test.sh blub/
cd blub/
git add test.sh
git pull

The pull will delete test.sh. It will only do this if you have no commit in the local repo. After adding a commit this won't remove test.sh (git either ignores it or reports a merge conflict)

The file is not lost. It's still in the Git repository as a dangling blob.

To recover the file:

$ git fsck
Checking object directories: 100% (256/256), done.
Checking objects: 100% (401/401), done.
dangling blob 541060d8292ff808c9715265d063f1bae220da7c
$ git show 541060d8292ff808c9715265d063f1bae220da7 > test.sh

This works as long as you did not issue git gc --prune=now afterwards.

Related Question