DEV Notes

Git pile

The unsorted and unorganized collection of various Git tips and tricks collected over several years.

Git default branch

git config --global init.defaultBranch main

NOTE: This could be essential, for example, for tools like cargo in rust.

Set Git editor

git config --global core.editor nano

Show last commit changes

git log -p -1

Show the last commit hash

git log --pretty="%h" -1

Check out a particular commit

git checkout <sha1>

Delete branches

git push origin --delete <branch-name>
git branch -D <branch-name>

Create a new branch from a specific commit

git checkout -b <branch> <sha1>

Limit cloning depth for large repos

git clone --depth=10 <repo-URL>

Add a remote origin to the local repository and push into new origin

git remote add origin <repo-URL>
git push -u origin main

Rename commit owner

git commit --amend --author="User1 <user1@example.com>" --no-edit
git push -f

NOTE: 1) it must be the last commit 2) you have to have appropriate commit rights

Full commit hash

git rev-parse <shot-commit-hash>

Create a new branch from a tag

git checkout -b <branch-name> <tag-name>

Remove a tag from a repository

git tag -d <tag-name>
git push origin --delete <tag-name>

Push a tag to a remote repository

git push origin tag <tag-name>

Unstage a specific file

git reset <file>

Unstage all files

git reset

Show changed file names per commit

git log --name-status

Show a particular commit

git show <sha1> --name-status

Create a patch from several commits

git format-patch <start-sha1>^..<stop-sha1> --stdout > changes.patch

Show short log

git log --pretty=oneline --abbrev-commit

Git submodule clone

During cloning no submodules are fetched by default. After the default clone do

git submodule init
git submodule update

or clone with submodules

git clone --recurse-submodules GIT_REPO_URL

Create a release history

git log --oneline <start-sha1>..<stop-sha1>

Diff between 2 branches

git diff branch_1...branch_2

Revert Git repository to a previous commit

git reset --hard HEAD~1

View the existing remotes

git remote -v

NOTE: Multiple remotes are possible

Add a new remote

it remote add <name> <url>

Push to a specific remote

git push <remote-name> <branch-name>

Rename the current branch

git branch -m <new-name>

Rename a branch while in another branch

git branch -m <old-name> <new-name>

Push the local branch and reset the upstream branch

git push origin -u <new-name>

Get a file from a commit or a branch

git restore -s <sha1> -- <some-file>
git restore -s <branch> -- <some-file>