Skip to content

Latest commit

 

History

History
1224 lines (950 loc) · 37.9 KB

Git commands.md

File metadata and controls

1224 lines (950 loc) · 37.9 KB

Git commands

Make sure you are in the directory of the cloned repository!

Also make sure the cloned repository is yours! If not, there will be an error message:

$ git push origin
remote: Permission to <other-user-name>/<repo-name>.git denied to <your-name>.
fatal: unable to access 'https://github.com/<other-user-name>/<repo-name>/': The requested URL returned error: 403

Create an ssh key

How do I avoid the specification of the username and password at every git push?

Create an access token

Creating a personal access token

Support for password authentication was removed. Please use a personal access token instead [duplicate]

When asked for password, key in the access token generated on Github(not password!).

Create an alias

Shortcuts for git commands

git config --global alias.<short> "<long>"

Create a repository on remote server

in remote server's abc\def folder:

mkdir <xxx>.git
cd <xxx>.git
git init --bare

on local machine:

git remote add origin "\\\\Servername\\abc\\def\\<xxx.git>"
git push origin master

list all remote version control base's name and website

(To check origin)

$git remote -v

Make a directory git repository

A new repo from an existing project

$git init
$git add *
$git commit

Clone a repository

https://stackoverflow.com/questions/67699/how-to-clone-all-remote-branches-in-git

$git clone https://github.com/<user-name>/<repo-name>.git

To clone into a specific directory:

$git clone https://github.com/<user-name>/<repo-name>.git <directory>

If you want to clone all branches, it already does it for you. You can check it with:

$git branch -a

And to start work on one branch, just:

$git checkout <branch-name>

Clone from windows server:

Cannot clone GIT repository on network drive

git clone "file:////Venus/aaa/bbb/proj1.git"
git clone --no-hardlinks "//Venus/aaa/bbb/proj1.git"
git clone file:////<ip-addr>/aaa/bbb/proj1.git

Just clone a folder from a repository

How do I clone a subdirectory only of a Git repository?

$mkdir <repo>
$cd <repo>
$git init
$git remote add -f origin <url>
$git config core.sparseCheckout true
$echo "some/dir/" >> .git/info/sparse-checkout
$git pull origin master

Just clone a branch of a repo

$git clone -b <branch-name> https://github.com/<user-name>/<repo-name>.git

Or:

git clone --single-branch --branch <branch-name> <remote-repo>

Reset a repo(Discard all commits)

Git: How to reset a remote Git repository to remove all commits?

rm -rf .git
git init
git remote add origin <url>
git push -f origin master

Synchronize(Reset) local repo with remote one

git: sync local repo with remote one

git fetch --prune #-p, --prune: After fetching, remove any remote-tracking branches which no longer exist on the remote.
git checkout <branch-name> #if there are new branches

If the commands above do not work, try:

git pull

Method 2:

Reset local repository branch to be just like remote repository HEAD

git fetch origin
git reset --hard origin/master
git clean -n -f

Note: git fetch will pull the branch that only exist in remtoe to local

Git fetch

How to 'git pull' without switching branches (git checkout)?

To fetch a remote branch(to pull a remote branch without checkout):

git fetch <remote_branch_name>
git fetch <remote> <src_branch>:<dest_branch>

To fetch all remote branches:

git fetch --all

Merge two repositories into one

How do you merge two Git repositories?

Rename a repository

How do I rename a Git repository?

List all branch and get current branch name

$git branch

List all branches, sort by commit time, descending

How can I get a list of Git branches, ordered by most recent commit?

git branch --sort=-committerdate 

List all remote branch

How do I list all remote branches in Git 1.7+?

$git branch -r

Change remote default branch

深入 Git:HEAD refs

git symbolic-ref HEAD refs/heads/<branch-name>

Discard unstaged changes

How do I discard unstaged changes in Git?

Undo working copy modifications of one file in Git?

$git checkout -- .

We can also specify the filename:

$git checkout -- <filename>

If git checkout not work, showing:

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
  (commit or discard the untracked or modified content in submodules)
        modified:   xxx (untracked content)

Then try:

rm -rf xxx

Showing:

Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        deleted:    xxx

And then:

git restore xxx

Finally the Changes not staged for commit block disappeared!

Switch branch in a bare repo

Git: Correct way to change Active Branch in a bare repository?

git symbolic-ref HEAD refs/heads/<branch-name>

Switch branch, discard all changes

Error when changing to master branch: my local changes would be overwritten by checkout

$git checkout -f <branch-name>

Stash local changes(before switching to another branch)

Stash暫存

How do you stash an untracked file?

# now we are on <original-branch-name>
git stash -u # this will also stash untracked files
# switch to <another-branch-name>
git checkout <another-branch-name>
# after the work is done on <another-branch-name>, change back to <original-branch-name>
# this is important!
# if you don't switch to <original-branch-name> first,
# the stashed changes will be applied to <another-branch-name>!!
git checkout <original-branch-name>
git stash list
git stash pop

Pop stash accidently, get the hash of the stash commit you dropped

How to recover a dropped stash in Git?

git fsck --unreachable | grep commit | cut -d" " -f3 | xargs git log --merges --no-walk --grep=WIP

Show the changes of the most recent stash

See what's in a stash without applying it [duplicate]

git stash show -p

Create a branch

$git checkout master Make sure you are in master branch every time you create a branch!!

$git checkout -b <branch-name> -b for create

$git push origin <branch-name> Push the branch from local to remote

Make a commit as a branch

How to create the branch from specific commit in different branch

How do I check out a particular version in Git from 'git log'?

git checkout <branch-name> <sha>

#or

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

Rename a branch

How do I rename a local Git branch?

$git branch -m <old-branch-name> <new-branch-name>
$git checkout <new-branch-name>
$git push origin :<old-branch-name>
$git push -u origin <new-branch-name>

Switch to another branch

$git checkout <branch-name>

Git: cannot checkout branch - error: pathspec '…' did not match any file(s) known to git

If there is an error:

error: pathspec 'xxx' did not match any file(s) known to git.,

one can use:

$git fetch

to make local repo updated with the remote one.

Make a commit a branch

Branch from a previous commit using Git

git branch branchname <sha>

Or:

git checkout <sha>
git switch -c <new-branch-name>

Move uncommited work to another branch

Move existing, uncommitted work to a new branch in Git

git switch -c <new-branch-name>

Delete a branch

$git checkout master
$git branch -d <branch-name>
$git push origin :<branch-name>

If you delete a branch from remote(GitHub website), Git remote branch deleted, but still it appears in 'branch -a', use the following command to remove the branch from local branch -r:

$git pull -p # git pull --prune

Delete a branch(only remote)

How to delete remote branches in Git

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

Recover a deleted branch

Can I recover a branch after its deletion in Git?

umayr/recover-deleted-branch.sh

MarioRicalde/git-recover-branch.md

# use this command to find the SHA1 for the commit at the tip of your deleted branch
git reflog
git checkout -b <deleted-branch-name> <sha>

Copy files between branches

How do I copy a version of a single file from one git branch to another?

git checkout <other-branch-name> <relative_path_to_file_or_dir>

List commits of a branch since its creation from master

git log master...<branch-name>

Check remote git log

Commit history on remote repository

git log origin/<branch-name>

work on two branches simultaneously

git working on two branches simultaneously

Git worktree: 同時開多個工作目錄

git worktree add ../<project-name>_<branch-name> <branch-name>

# work on that branch
cd ../<project-name>_<branch-name>
git commit ...

# after commiting, one can delete the directory safely
rm -rf ../<project-name>_<branch-name>

# notify git that the secondary worktree is removed,
# so we can checkout <branch-name> in the old directory
git worktree prune

Fork and then create a pull request

Follow the instructions here: https://help.github.com/articles/creating-a-pull-request-from-a-fork/

Apply unmerged pull request to own fork

How to apply unmerged upstream pull requests from other forks into my fork?

  1. If you don't want it to be merged to your master branch, first create a new branch
  2. Go to the webpage of the branch from other fork(which is the branch you want to apply)
  3. Select New Pull Request
  4. Choose the correct repo name and branch name
  5. Click Create Pull Request
  6. Merge the pull request

Add folders or files, commit, and then push(Git doesn't allow you to commit empty folders, the workaround is to add .gitkeep file into them)

$git add <folder-or-file-name>
$git commit
$git push origin <branch-name>

Changes not staged for commit even after git add

If got Changes not staged for commit even after using git add, one can try change to the specific folder and then use git add again.

Add part of file

Commit only part of a file's changes in Git

git add --patch <filename>
git add -p <filename>

git commit, specify author and email

How can I change the author name / email of a commit?

git commit --author="John Doe <[email protected]>" # the <> are required!

modify commit message

How to Change a Git Commit Message To modify the commit message of last commit:

$ git commit --amend -m "New commit message."

Track items but not add

How to track but not stage and how to unstage but not untrack?

git add -N <folder-or-file-name>

Sign off

First set user name and email and then:

git commit -s

Revert git add

How can you undo the last git add?

$git reset -- <folder-or-file-name>
$git reset #revert all added folders or files

Add empty folders

How can I add an empty directory to a Git repository?

Just add .gitignore in that empty folder, so GitHub will keep it.

Make .gitignore take effect

.gitignore is ignored by Git

$git rm -r --cached .
$git add .
$git commit -m "fixed untracked files"

Make git ignore lines matching specific pattern

How to tell git to ignore individual lines, i.e. gitignore for specific lines of code [duplicate]

Create <project root>/.git/info/attributes and then add into the file:

*.cpp filter=gitignore

Use git config to define the filter named gitignore:

git config --global filter.gitignore.clean "sed  '/View.*\(.*\);/d'"
git config --global filter.gitignore.smudge cat

Make git ignore file mode changes

How do I make Git ignore file mode (chmod) changes?

git config core.fileMode false

List all files under source control

Git - List all files currently under source control?

git ls-files

Untrack files

Untrack files from git temporarily

git rm -r --cached <folder-or-file-name>

Then you can see when using git commit, the file or folder moves from Changes to be committed part to Untracked files part.

Remove files from git repo and the file system

How can I delete a file from a Git repository?

git rm -r <folder-or-file-name>

Unstage files

Why are there two ways to unstage a file in Git?

git reset -- <filePath>

Then you can see when using git commit, the file or folder moves from Changes to be committed part to Changes not staged for commit part.

Delete files and then commit

Ref : Removing multiple files from a Git repo that have already been deleted from disk

$git add -u :/
$git commit
$git push origin <branch-name>

Move commits to an existing branch

Move the most recent commit(s) to a new branch with Git

Assume you have commited to master, but actually you want to commit to

git checkout <existing-branch-name>
git merge master
git checkout master
git reset --hard HEAD~3 # Go back 3 commits. You *will* lose uncommitted work.

Move commits to a new branch

Move the most recent commit(s) to a new branch with Git

Assume you have commited to master, but actually you want to commit to

git branch <branch-name> # on master branch
git reset HEAD~1 # on master branch
git checkout <branch-name>

Make current branch master branch

Make the current Git branch a master branch

git checkout <better-branch>
git merge --strategy=ours master    # keep the content of this branch, but record a merge
git checkout master
git merge <better-branch>           # fast-forward master up to the merge

Undo git remote add upstream

$git remote rm upstream

show origin

$git remote show origin

add origin

$git remote add <remote-name> "//xxx/yyy/zzz.git"

One can use this method to pull a branch from a forked repository.

set origin(change remote url)

How to change the URI (URL) for a remote Git repository?

$git remote set-url origin "//xxx/yyy/zzz.git"

fatal: remote origin already exists.

$git remote rm origin

get the url of origin

How can I determine the URL that a local Git repository was originally cloned from?

$git config --get remote.origin.url

Sync your forked repository

$git remote add upstream <the-url-of-upstream-repo>
$git fetch upstream
$git checkout master
$git merge upstream/master
$git push origin master

If a branch in upstream repo doesn't exist in forked repo, use the same way to sync it.

Reset your <branch-name> in forked repository

$git remote add upstream <the-url-of-upstream-repo>
$git fetch upstream
$git checkout <branch-name>
$git reset --hard upstream/master
$git push origin <branch-name> --force #--force solves non-fast-forward error

Sync a branch with master branch

$git pull origin <branch-name>
$git checkout <branch-name>
$git merge master
$git push origin <branch-name>

Merge a local branch <branch-feature> into another local branch <branch-base>

$git checkout <branch-base>
$git merge <branch-feature>
$git push origin <branch-base>

If met with the problem merge: <branch-feature> - not something we can merge, try $git checkout <branch-feature> and then repeat the commands above.

If there is a conflict:

Auto-merging xxx.cpp
CONFLICT (content): Merge conflict in xxx.cpp
Automatic merge failed; fix conflicts and then commit the result.

Then edit the xxx.cpp to resolve the conflicts, and then:

$git add xxx.cpp
$git commit

Undo merge

Undo a Git merge that hasn't been pushed yet

# find out the commit just prior to the merge, get its sha
$git reflog
# reset
$git reset --hard <sha-of-a-commit>

Pull a specific branch from remote to local

$git pull origin <branch-name>

Rebase a branch to origin

Git push rejected after feature branch rebase

Rebase a branch after updating master:

//update master branch
$git checkout <branch-name>
$git rebase master
$git push --force-with-lease origin <branch-name>

or

$git fetch
$git rebase master
$git pull origin <branch-name> # to solve non-fast-forward error
$git push origin <branch-name>

Import a repository(This is a hack to fork a repo but detach their dependency)

Click on the '+' sign on the upper right corner of Github webpage(next to your avatar)
Click on "Import repository"
In "Your old repository’s clone URL", paste the url of repo you want to import
Give it a new name and click "Begin import"
After the process is done, Github will send you a email confirming with that

Restore a file to specific commit version

How can I reset or revert a file to a specific revision?

git checkout <sha-of-a-commit> -- /file1/to/restore

Revert a commit

(This will create a new commit) $git revert <sha-of-a-commit>

Undo a commit and make them unstaged

Move (or "Undo") last git commit to unstaged area [duplicate]

git reset HEAD^ # move them to unstaged area

or:

git reset --soft HEAD^ # move them to staged area

Revert a commit and make them untracked

Undo git add, commit and push WITHOUT losing untracked files

$ git log
# copy hash of the commit that you accidentally pushed as HASHFROMSTEPTWO
$ git revert HEAD
$ git push
$ git cherry-pick -n HASHFROMSTEPTWO

Revert multiple commits to a specific point

(This won't create new commit, it just remove the specific commits)

$git checkout <branch-name>
$git reset --hard <sha-of-a-commit>
$git push origin <branch-name> --force

Or using git rebase mentioned below.

Remove commits

Remove specific commit

How to remove commits from a pull request

$git checkout <branch-name>
$git rebase -i HEAD~n # this will include `n` last commits in interactive rebase
# a nano editor will show up
# the work `pick` precedes every commit
# now replace `pick` with `drop`
# then write out(Ctrl+O) and exit(Ctrl+X)
$git push origin <branch-name> --force

Apply a commit onto another branch

How to copy commits from one branch to another?

$git cherry-pick <sha-of-a-commit>

This apply the specific commit onto current branch.

Check status with modification date

git status - list last modified date

git status -s | while read mode file; do if [ "$mode" != "D" ]; then echo $mode $file $(stat -c %y $file); fi; done

Grep in history commits

How to grep (search) committed code in the Git history

git grep <regexp> $(git rev-list --all)

Grep for specific files

git grep by file extensions

git grep res -- '*.cpp'

Compare, ignore ^M

git-diff to ignore ^M

Either one of them:

$git diff --ignore-space-at-eol
$git diff --ignore-space-change
$git diff --ignore-all-space

Compare, show special chars

how to use git diff show some invisible characters differences?

git diff | cat -A

Compare, char by char

How can I visualize per-character differences in a unified diff file?

git diff --color-words=. <filename>

Compare two branches

$git diff <branch-name1> <branch-name2>
# specify the file to compare
$git diff <branch-name1> <branch-name2> <filename>

To compare two branches on Github website, go to:

https://github.com/<user_name>/<repo_name>/compare/<branch1>...<branch2>

Compare two branches, file name only

Showing which files have changed between two revisions

Compare against :

git diff --name-status <branch-name>

Or comparing two branches:

git diff --name-status <branch-name1>..<branch-name2>

Compare current state and last commit

See diff between current state and last commit

$git diff

or

Finding diff between current and last version

$git diff HEAD

How to see the changes in a Git commit?

$git show <sha-of-a-commit>

Ignore a specific directory(Exclude a directory from git diff):

$shopt -s extglob
$git diff !(<dir_name>)

Compare, only show the filenames

Can I make 'git diff' only show the changed file names and line numbers?:

$git diff --name-only

Compare staged changes with last commit

How do I show the changes which have been staged?

$git diff --cached

Check git branch graph

$git log --oneline --graph

To see log info of all branches:

$git log --oneline --graph --branches

git log, only show commit ids

git log show one commit id only

git log --pretty=format:"%h"

Only show commit ids:

git log --pretty=format:"%h" -<n>

find the branch from commit id

How to find the branch from commit id

git branch --contains <commit>

Compare commits

Comparing commits

First find out the SHA codes of the two commits, and then open https://github.com/<repo_owner>/<repo_name>/compare/<commit_sha1>..<commit_sha2> in the browser.

Get number of lines changed between two commits

How can I calculate the number of lines changed between two commits in git?

$git log --stat
$git diff --shortstat <branch-name>

Add equation into Github README.md

How to show math equations in general github's markdown(not github's blog)

Write your equation in iTex2Img, find its url, and then add the following into your README.md:

![equation](http://www.sciweavers.org/tex2img.php?<somewhere_link_to_your_image>)

Add image into Github README.md

Add the following into your README.md:

![image](<image_url>)

To resize(Changing image size in Markdown):

<img src="<image_url>" alt="drawing" width="200"/>

check git config

Easiest way to reset git config file

# config only for this repo
# stored in <repo>/.git/config
git config --local --list
# global config
# stored in ~/.gitconfig
git config --global --list

set user name and email

git config --global user.name "John Doe"
git config --global user.email [email protected]

change user name and email of last commits

How to amend several commits in Git to change author

git -c "user.name=John Doe" -c "[email protected]" rebase -i HEAD~4 -x "git commit --amend --author 'John Doe <[email protected]>' --no-edit"

Note the -c "user.name=John Doe" -c "[email protected]" to temporarily set committer info. Override configured user for a single git commit

If there is following error:

invalid upstream HEAD~4

Git: Needed a single revision error

It means there are less than 4 commits, it can be solved with:

git rebase -i --root ...

To also change commiter name: How to change the author and committer name and e-mail of multiple commits in Git?

change user name and email of matching commits from all branches

Changing author info

git filter-branch -f --env-filter '
OLD_NAME="jack"
CORRECT_NAME="james"
CORRECT_EMAIL="james.example.com"
if [ "$GIT_COMMITTER_NAME" = "$OLD_NAME" ]
then
    export GIT_COMMITTER_NAME="$CORRECT_NAME"
    export GIT_COMMITTER_EMAIL="$CORRECT_EMAIL"
fi
if [ "$GIT_AUTHOR_NAME" = "$OLD_NAME" ]
then
    export GIT_AUTHOR_NAME="$CORRECT_NAME"
    export GIT_AUTHOR_EMAIL="$CORRECT_EMAIL"
fi
' --tag-name-filter cat -- --branches --tags

set git proxy

为 git bash 设置代理

git config --global http.proxy "http://127.0.0.1:1080"
git config --global https.proxy "https://127.0.0.1:1080"

unset git proxy

Git: How to remove proxy

git config --global --unset https.proxy
git config --global --unset http.proxy
git config --unset http.proxy
git config --unset https.proxy

If it doesn't work, use:

git config --global --edit

and clean the field proxy, like:

[http]
[https]
[http "https://github.com"]
        proxy =
[https "https://github.com"]
        proxy =

sync tags from upstream

How do I sync tags to a forked github repo?

git fetch --tags upstream
git push --tags

upload large file(> 100MB)

Git Large File Storage

For installation, please check https://github.com/keineahnung2345/linux-commands/blob/master/Linux%20packages.md#git-lfs.

fatal: The remote end hung up unexpectedly

Git, fatal: The remote end hung up unexpectedly

git config --global http.postBuffer 524288000

Create a patch

format-patch製作patch及git am匯入patch

What is the difference between 'git format-patch and 'git diff'?

Generate patch of last commit:

git diff <commit_sha_1> <commit_sha_1> > xxx.patch
# git format-patch -n, n for number of commits
git format-patch -1

To create a patch used by redmine, ref: How to create patch series on Mercurial and Git:

git format-patch -k --stdout -1 > xxx.patch

Apply a patch

How to apply a patch generated with git format-patch? and 4.2.1 git am patch手动解决冲突的办法

git apply --reject xxx.patch

It shows:

error: patch failed: aaa.txt

Modify aaa.txt to resolve the conflict:

vim -O aaa.txt.rej aaa.txt

And then commit:

git add <files> # but not adding *.rej
git commit

Public and private repo syncing

Having a private branch of a public repo on GitHub?

Submodule

List submodules

List submodules in a Git repository

cat .gitmodules
[submodule "source/xyz"]
        path = source/xyz
        url = https://<ip-addr>/<path>
git config --file .gitmodules --name-only --get-regexp path
submodule.source/xyz.path
git config --file .gitmodules --get-regexp path | awk '{ print $2 }'
source/xyz

Update submodule info

After editing .gitmodules, run the following to make it take effect:

git submodule sync --recursive

Add submodule

git submodule add <remote_repository> <local_path>
git add .
git commit

When adding submodule, if there's following error:

'xxx' already exists in the index

According to Issue with adding common code as git submodule: "already exists in the index", just type git rm xxx.

clone with submodule

How to "git clone" including submodules?

git clone --recursive git://github.com/foo/bar.git

repo already cloned, only clone submodule

How to "git clone" including submodules?

git clone git://github.com/foo/bar.git
cd bar
git submodule update --init --recursive

update submodule

git submodule update --remote --merge --recursive

And then commit:

git add .
git commit -m "update submodule"
git push

check submodule version

How to see which commit a git submodule points at

git submodule status
4568ae1fee552122f39f55d7be03b03a8ab744334 <submodule_name> (heads/master)

Or:

git ls-tree HEAD | awk '$2 == "commit"'
160000 commit 4568ae1fee552122f39f55d7be03b03a8ab744334  <submodule_name>

remove submodule

git rm <submodule_relative_path>
# remove remaining records from .git/modules
rm -rf .git/modules/<submodule_relative_path>
# remove remaining records from .git/config
git config --remove-section submodule.<submodule_relative_path>
# check
ls .git/modules
git config -l

SSL: no alternative certificate subject name matches target host name

How do I set GIT_SSL_NO_VERIFY for specific repos only?

git config --global http.sslVerify "false"

fatal: This operation must be run in a work tree

Why am I getting the message, "fatal: This operation must be run in a work tree?"

git config --unset core.bare

HEAD detached from xx00000

git checkout master

error: invalid path(Windows)

github/git Checkout Returns 'error: invalid path' on Windows

git config core.protectNTFS false

Make git diff works on UTF-16 file

Diff .strings files in Git

Can I make git recognize a UTF-16 file as text?

.gitattributes中:

*.<file_extension> diff=utf16 eof=crlf

.git/config中加入:

[diff "utf16"]
        textconv = "iconv -f UTF-16LE -t UTF-8"