git

Adventures with Git

Updated

A compilation of various git commands as I went on with my daily development work is listed here. I plan to keep this page updated as I explore more.

  • Clone with submodules: git clone --recurse-submodules [repo]

  • Clone a single branch: git clone --single-branch -b [branch name] [repo]

  • Add or update submodules to an already cloned project:

    • git submodule update --init --recursive (add)
    • git submodule update --recursive --remote (update)
  • Delete local branches non-existent on remote: git branch -vv | grep 'origin/.*: gone]' | awk '{print $1}' | xargs git branch -d

  • Rebase a feature branch onto main:

    1. Check out and pull both branches.
    2. git checkout main && git pull
    3. git rebase [feat_branch]
    4. Also, rebase with origin if needed git rebase origin/main
    5. Resolve conflicts if any and do git add .
    6. git rebase --continue
  • Cherry pick:

    1. Pull both branches and checkout main.
    2. Gather SHA’s of commits you’d like to pick from your feat branch.
    3. Do git cherry-pick [COMMIT_SHA] (note: COMMIT_SHA should be taken in the oldest first order)
    4. Resolve conflicts if any and do git add .
    5. git cherry-pick --continue
  • Revert a commit:

    • git revert HEAD (will revert the topmost commit)
    • git revert [SHA]
  • Push a new branch to remote: git push --set-upstream origin [local_branch]

  • Reset a file in local: git checkout HEAD -- [path to file]

  • Check which git tag has a given commit: git tag --contains [SHA]

  • Create a patch from changes:

    • git diff > [patch_name.patch] for unstaged changes.
    • git diff --cached [patch_name.patch] for staged changes.
    • git diff HEAD [patch_name.patch] for both staged and unstaged changes.
  • Create a patch from commit: git format-patch -1 HEAD (-1 signifies one commit to be added in patch)

  • Apply a local patch: git apply [patch_path]

  • Apply a patch from commit: git am -3 < file.patch

  • Stash only unstaged changes: git stash -k