Here are some of the git commands that I most often use are presented here with use cases. This is not an exhaustive list of git commands.

  • Create a local repo and push to remote repo
    • Create a new repo
      • git init - Initializes a new local git repo with local branch name as main
    • Push local repo to remote
      • Prerequisite: Create a remote repo in github/gitlab/bitbucket
      • Connect/Link local repo to remote repo
        • git remote add origin <github-repo-link>
        • Example: git remote add origin git@github.com:<user-name>/<repo-name>.git
      • git pull origin main
      • git push -u origin main

  • Create a local feature branch, remote feature branch, and link local branch to remote branch
    • Create a local branch
      • git checkout -b <local-branch-name>
    • When you do git push
      • Git complains:

        The current branch <local-branch-name> has no upstream branch.

    • Time to create a remote branch to do any push
      • git push -u origin <remote-branch-name> // -u shorthand for --set-upstream
        • Example: git push -u origin dev/feature
    • The above command will create a remote branch and links the local-branch with remote branch, thereby enabling us to do git push easily without -u argument

  • Create a local feature branch, link to remote branch in one go
    • git checkout -b <localbranch> <remote-branch> // This will automatically add the –track option
    • Example: git checkout -b dev/feature1 origin/dev/feature1

  • Discard/Revert all your local commits and reset local branch to last stable commit of remote branch
    • Prerequisite: Ensure shell/prompt is in local branch
    • git reset --hard origin/<remote-branch-name>

  • Revert to a specific commit: Erase history of some commits
    • git reset --hard <commitId>
    • git push -f // -f shorthand for --force -> force updates

  • Move all changes from staging to unstaged area
    • git reset

  • Move a specific file from staging to unstaged area
    • git restore --staged <Path of the file you wanna restore>

  • Replace all changes in unstaged area with latest from upstream
    • git checkout .

  • Replace a specific file in unstaged area back with latest from upstream
    • git checkout <abs-path-filename>

  • Remove the untracked file/directories
    • git clean -f // cleans all untracked files
    • git clean -f -d // cleans all untracked directories

  • Show the files changes for a given commit
    • git show --pretty="" <commit-hash> --name-only

  • Delete a local branch
    • git branch -D <local-branch-name>
      • D indicates delete a local branch even if it is not merged
  • Delete a remote branch
    • git push --delete origin master - This will delete the remote branch

  • Merge/Sync local branch (A) with remote branch (A)
    • Ensure prompt/shell in local branch
    • git checkout branch-A
    • git pull origin/branch-A // Syncs local branch-A with remote origin/branch-A
    • Or simply git pull // This requires local branch to be linked with remote branch

  • Merge/Sync local branch(A) with remote branch (B) Example: B can be master/dev branch
    • Ensure prompt/shell in local branch
    • git pull origin <remote-branchname>
    • Example:
      • git checkout feature1
      • git pull origin development // Syncs local branch feature1 with remote development branch

  • Switch between branches, if you are in Branch (A) and want to switch to another Branch (B)
    • git checkout <branch> // This will simply switch your local branch
    • Or git switch <branch> // Starting from git2.23

  • Update commit message - Works only if it’s not already pushed to upstream
    • git commit --ammend

  • Stash commands
    • To view the stashed file changes on console
      • git stash show -p 18 // here 18 is your stash number
    • git stash -u(includes untracked files as well) -m <named your stash>
      • Stashes all your staged and unstaged commits
      • Example: git stash -u -m "srk-local-automation"
    • git stash list
      • Lists all your stashes
    • git stash show
      • You can view the summary of a stash
      • Lists all the files present in this stash
    • git stash apply <number given to your stash>
      • Doesn’t remove the last saved stash, helps for later reuse
      • Example: git stash apply 0 or git stash apply stash@{0}
    • Export the stash: git stash show -p --binary > srk-local-changes.patch
      • This will create an exportable file srk-local-changes.patch which you can apply on other repos
    • Import the stash: git apply srk-local-changes-patch
      • This will import the patch file srk-local-changes-patch, meaning it is added to current stash list
    • git stash pop <name of your stash>
      • Removes the last saved stash from top of stash and applies

  • Tag commands
    • Create an annotated tag
      • git tag -a v0.1.0
    • List all the tags
      • git tag
    • Get the details of a specific git tag
      • git show v0.1
    • Note: git push doesn’t automatically push your tags into the remote server. So you have to push the tag explicitly using the below command
      • git push origin <your-tag>
      • Example: git push origin v0.1.0
    • Deleting tags
      • git tag -d v0.1.0
    • Checkout tags
      • git checkout v0.1.0


  • Making verified/Signed git commits
    • Read: https://docs.github.com/en/authentication/managing-commit-signature-verification/checking-for-existing-gpg-keys?platform=linux
    • Generate a gpg key
      • gpg --full-generate-key
        gpg (GnuPG) 2.2.40; Copyright (C) 2022 g10 Code GmbH
        This is free software: you are free to change and redistribute it.
        There is NO WARRANTY, to the extent permitted by law.
      
        Please select what kind of key you want:
          (1) RSA and RSA (default)
          (2) DSA and Elgamal
          (3) DSA (sign only)
          (4) RSA (sign only)
          (14) Existing key from card
        Your selection? 1
        RSA keys may be between 1024 and 4096 bits long.
        What keysize do you want? (3072) 3072
        Requested keysize is 3072 bits
        Please specify how long the key should be valid.
                0 = key does not expire
              <n>  = key expires in n days
              <n>w = key expires in n weeks
              <n>m = key expires in n months
              <n>y = key expires in n years
        Key is valid for? (0) 2y
        Key expires at Wed 10 Mar 2027 11:36:08 PM IST
        Is this correct? (y/N) y
      
        GnuPG needs to construct a user ID to identify your key.
      
        Real name: srk
        Name must be at least 5 characters long
        Real name: sairaghavak
        Email address: xxxxx
        Comment: 
        You selected this USER-ID:
            "sairaghavak <xxxxx>"
      
        Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? O
        We need to generate a lot of random bytes. It is a good idea to perform
        some other action (type on the keyboard, move the mouse, utilize the
        disks) during the prime generation; this gives the random number
        generator a better chance to gain enough entropy.
        We need to generate a lot of random bytes. It is a good idea to perform
        some other action (type on the keyboard, move the mouse, utilize the
        disks) during the prime generation; this gives the random number
        generator a better chance to gain enough entropy.
        gpg: directory '~/.gnupg/openpgp-revocs.d' created
        gpg: revocation certificate stored as '~/.gnupg/openpgp-revocs.d/572E1DBF298994CDE9417E1F538D83FE7669C935.rev'
        public and secret key created and signed.
      
        pub   rsa3072 2025-03-10 [SC] [expires: 2027-03-10]
              572E1DBF298994CDE9417E1F538D83FE7669C935
        uid                      sairaghavak <xxxxx>
        sub   rsa3072 2025-03-10 [E] [expires: 2027-03-10]
      
    • List all the keys

      gpg –list-secret-keys –keyid-format=long

      • Sample Output

            ~/.gnupg/pubring.kbx
            ----------------------------
            sec   rsa3072/538D83FE7669C935 2025-03-10 [SC] [expires: 2027-03-10]
                  572E1DBF298994CDE9417E1F538D83FE7669C935
            uid       [ultimate] sairaghavak <xxx>
            ssb   rsa3072/FD9465D77FE10649 2025-03-10 [E] [expires: 2027-03-10
        
    • Export the key that you’d like to add to your github
      • gpg –armor –export

        Example: gpg –armor –export 538D83FE7669C935

      • This will print the public key, just copy full output staring with text like “—–” to last string and upload it under your github “ssh and GPG keys” -> Add GPG keys section
    • Also, ensure that you have it in ~/.gitconfig

      [user]
          signingkey=538D83FE7669C935
      [gpg]
          program=/usr/bin/gpg
      
    • To override the signing key for a specific repo(Let’s say your personal gitlab/github account) have this under the repo specific ./git/config

      [user]
          name=sairaghavak
          email=<your email matching the GPG key>
          signingKey=<your-key-id>
      [commit]
          gpgsign=true
      
    • Create a file gpg-agent.conf under ~/.gnupg

      use-agent
      allow-loopback-pinentry
      
    • Add this line at the end of your ~/.bashrc or ~/.zshrc

      export GPG_TTY=$(tty)
      
    • Refresh bash prompt with source ~/.bashrc
    • Do a signed Commit from CLI(Some home from VScode UI it isn’t working in my case)

      git commit -S -m “"

References:

  1. Git-The Stupid Content Tracker