Undo a Single File in Git

I just had a need to undo (reset) a single file while I was working on multiple files. I was just testing stuff in different files and I wanted to undo the changes in a single file. Here is what you can do.

git checkout HEAD -- myfile

I think I did this before but I had forgotten it. I’m hoping to remember it by blogging it and help someone out there. 🙂

How to Start a Local Git Repo and Upload it to GitHub

You start to write code locally in a directory and you want to keep track on file changes in a Git database and then upload (push) it to GitHub.

You have some files already in a directory and you start a Git repo locally by executing git init.

Now stage it and commit it.

git add .

git commit -m 'initial commit'

Once you create a repo on GitHub, you have a link to the GitHub repo in the page. Using that SSH repo link, you can push it to GitHub.

Now configure the remote repo in local Git database.

git remote add origin git@github.com:hiriumi/oci-resources.git

And then, push it to the upstream repo.

git push --set-upstream origin master

You won’t need --setup-upstream origin master from the subsequent pushes.

git push to the Current Branch

Quite often when you are working in a branch in Git, you want to push the committed stuff to the server side. You’d do the following.

git push origin my_long_branch_name_that_has_description_of_this_branch

You can set a global option for “git push” to push the code to the current branch by executing the following command.

git config --global push.default current

Now you can just type…

git push

This saves me so many keyboard typing and copy and paste of the current branch names.

How to Pull Remote Branch in Git

There may be a branch someone else pushed to the server and you want to work with it. What should you do? Here is how you can accomplish.

First, create a local branch out of the remote branch.

$ git fetch origin remote-branch-name:remote-branch-name

Now checkout the branch.

$ git checkout remote-branch-name

You don’t really want to do something like…

$ git pull origin remote-branch-name

This will get the source from the remote-branch-name branch and merge the code into the master (or whichever you have checked out) branch automatically unless you have a conflict. I had to do git reset –hard [the commit ID] to undo it.