Git Guide
This article is a collection of git commands that I commonly use. Essentially it is a personal cheat sheet for when I am doing stuff with git.
Let's start out with some basic commands:
git init
initializes a local git repository in the current folder.
git add -p
asks you for each change that you have made whether you want to stage it for a commit.
git commit -m "message"
commits the currently staged changes with the commit message as the text between the quotes.
git log
see a list of commits in this repository.
Git can work fine locally, but you can also push it to a remote server, which helps with collaboration. Here are a couple of commands:
git clone
git remote -v
prints the current remote URLs and their names.
git remote add origin url_of_remote
git remote get-url name_of remote
git remote set-url name_of_remote new_url_of_remote
git push
pushes current changes to the remote repo.
git pull
pulls changes from the remote repo to your local folder.
Add to ~/.gitconfig:
[push]
default = simple
[user]
name = Marno
email = [email protected]
[alias]
graph-full = log --graph --all --decorate
graph = log --graph --oneline --all --decorate
Worktrees:
mkdir NAME
cd NAME
git clone --bare URL git
cd git
git worktree add ../BRANCH BRANCH
cd ..
Submodules
Submodules are a great feature that allows nesting of git repositories:
git submodule update --recursive --init
if you have cloned a repository that contains submodules, you can use this command to initialize all of them recursively.
git submodule add remote_url destination_folder
if you want to add a submodule to one of your repositories you can use this command.
Removing a git submodule:
-
mv a/submodule a/submodule_tmp
-
git submodule deinit -f -- a/submodule
-
rm -rf .git/modules/a/submodule
-
git rm -f a/submodule
Branches
To merge branch1 into branch2:
git checkout branch2
git merge branch1
Create a new branch branch2 based on content of branch1:
git checkout branch1
git checkout -b branch2
If you have a commit on a detached HEAD and want to add it to branch1:
git checkout -b tmp_branch
git checkout branch1
git rebase tmp_branch
git branch -d tmp_branch
Amending history
If you would like to see a diff between two commits look up their hex values in git log and use the following command (--word-diff is optional and is useful for written text):
git diff --word-diff commit1..commit2
To change just the last commit:
git commit --amend
If you have changes you don't want to commit, adding files to the .gitignore
file is one option.
Another is stashing your work:
git stash push
git stash list
git stash pop
Rebasing, replace X by the amount of commits you want to go back:
git rebase -i HEAD~X
git push -f