Git Basic Usage

Git has become the main version control system for our code. This means we need a good understanding of Git to maintain/contribute/develop any software nowaday.

git config Initial Config

Is this first time you use Git? Then you should start setting up your email and name, which will be used in all your projects.

git config --global user.name "Your Name"
git config --global user.email you@yourdomain.com

Start up

We must ask ourselves if we are importing an existing project or creating a new one.

Git Clone
git clone [url]
Git Init
git init
GitHub
git init
git add .
git commit -m 'First commit'
git remote add origin https://github.com/user/project
git push origin master

git add Stagging

The staging area or git add has a primary function, is to promote pending changes in the working directory. After you're happy with changes or staged snapshot, you commit them to the project history.

git add [file]    # Add a single file or directory
git add .         # All files and directory
git add -p        # Interactive mode
Status

Get all information about repo's current state.

git status
Diffing

By default git will show you any uncommitted changes since the last commit.

git diff
Revert

Restore files from current index unstagging them to last committed state.

git reset [file] [*.txt] [/dir]
git reset -p       # Interactive mode

Or simply checkout the file.

git checkout -- file.txt

git commit Ok, all look works

Once we saved a snapshot of the current project state with git add, the git commit command is then used to register current state to the repository commit history.

git commit -m 'First commit'

Or you can add changes to last commit:

git commit --ammend

git merge Branching and merge

Git merge will combine multiple commits into one unified history. In the most frequent use cases, merging is used to combine two branches. We should follow merge-commit pattern to keep an initial and end point in the history.

git checkout -b newfeature
git add .
git commit -m 'Added new feature'
git checkout master
git merge newfeature -m 'Merged newfeature into master'
git push master

git pull Be up-to-date!

Merge remote upstream changes into your local repository with git pull. This command is a combination of two other commands, git fetch followed by git merge. In the first stage git will retrieve latest changes where HEAD is pointed at. Once the content is downloaded, git pull will enter a merge workflow.

git pull

Sometimes we have an upstream that rebased/rewound a branch we're depending on. This can be a big problem causing messy conflicts for us if we're downstream. We can solve it rebasing:

git pull --rebase

git reset Ouch! I did a mistake

When we want to restore entire branch to last commit we should:

git reset --hard HEAD~1

You can undo n commits using HEAD~n. Be careful! Deletes local changes

Further reading