Skip to content

frequently used commands

some git commands i frequently use but sometimes keep forgetting.


restore a file

git restore --source <branch_name> <file_relative_path>

restore to main branch

git restore --source main pages/docs/index.tsx

restore to the last commit in main

git restore --source master~1 pages/docs/index.tsx

restore to last commit in current branch

git restore -source=HEAD~1 pages/docs/index.tsx

restore a folder

git restore --source <branch_name> <folder_relative_path>
git restore -source=HEAD~1 pages/docs

references : git-tower


init rebase

git rebase <upstream> <branch_name>

pull and rebase

git pull --rebase <upstream> <branch_name>

after resolving conflicts and add to stage

git rebase --continue

to cancel rebase process

git rebase --abort

references : git docs

relocate last commit to another branch

when you accidentally commit to branch_a but actually you want to commit it in branch_b

git checkout branch_a
git reset HEAD~1

git checkout -b branch_b
# or
git checkout branch_b

git add --all
git commit -m "commit message"

remove created tag

git tag -d <tag_name>

rename a tag

create an tag alias with a new name

git tag old_name new_name

remove the old tag locally

git tag -d old_name

remove the tag on the remote, with a checkout

git remote -v

the third argument is your remote repo. in our example, origin

git push origin :refs/tags/old_name

finally, add the new tag to the remote repo. the new tag will not be added until this is done.

git push origin --tags

repeat this process in all remotes.

reference: stackoverflow

use ssh key to sign a commit

this only works with git 2.34.0 or newer and openssh 8.0 or newer.

configure git to use ssh for commit signing, and tell git which key must be used

git config --global gpg.format ssh
git config --global user.signingkey ~/.ssh/examplekey

use the -S flag when signing your commits:

git commit -S -m "My commit message"

or tell git to sign your commits automatically

git config --global commit.gpgsign true

use gpg to sign a commit

list all your keys

gpg --list-secret-keys | grep ^sec
sec   3185S/7DD21DBA 2014-05-06 [expires: 2015-05-05]
#           ^^^^^^^^

we need this hexadecimal value after the slash. add this value to your git config.

git config --global user.signingkey 7DD21DBA

replace 7DD21DBA by your hexadecimal value from the last command. to use this key in only one repo, run the last command without the --global. when you do an commit, add the -s option.

git commit -S -m 'Testing an signed commit.'

to confirm:

git log --show-signature

getting the difference between two repositories

# go to repo_a
cd /home/user/repo_a

# add the repo_b as a remote
git remote add -f b /home/user/repo_b

# see the differences on branch main
git diff main remotes/b/main

# when you're done, remove the remote
git remote rm b

reference: git: getting the difference between two repositories