Git common commands

1. Base

1.1 New code base

1
2
3
4
5
# Initialize the local repository
git init

# Clone remote repository
git clone [url]

1.2 Configure

Git’s settings file is .gitconfig, it is usually in the user home directory, for instance C:\Users\[YourUsername]\

1
2
3
4
5
6
# Display the current Git configuration
git config --list

# Set user information when submitting code
git config --global user.name "HardyHu"
git config --global user.email 1243971719@qq.com

1.3 Add/Delete files

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# Add the specified file to the staging area
git add [file1] [file2] ...

# Add the specified directory to the staging area, including subdirectories
git add [dir]

# Add all files in the current directory to the staging area
git add .

# Before adding each change, it will ask for confirmation
git add -p

# Delete the workspace file and put this deletion into the staging area
git rm [file1] [file2] ...

1.4 Code submission

1
2
3
4
5
6
7
8
9
# Submit the staging area to the warehouse area
git commit -m [message]

# Submit the specified file in the staging area to the warehouse area
git commit [file1] [file2] ... -m [message]

# Submit the changes in the workspace since the last commit, directly to the warehouse area
git commit -a

1.5 Branch

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# List all local branches
git branch

# List all remote branches
git branch -r

# List all local and remote branches
git branch -a

# Create a new branch, but still stay in the current branch
git branch [branch-name]

# Create a new branch and switch to it
git checkout -b [branch]

# Create a new branch pointing to the specified commit
git branch [branch] [commit]


1.7 View information

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Show files with changes
git status

# Display the version history of the current branch
git log

# Display the commit history, and the files changed with each commit
git log --stat

# Search submission history, by keyword
git log -S [keyword]

# ...

1.8 Remote sync

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Download all changes from the remote repository
git fetch [remote]

# Show all remote repositories
git remote -v

# Display information about a remote repository
git remote show [remote]

# Fetch changes from remote repo and merge with local branch
git pull [remote] [branch]

# Upload the local specified branch to the remote warehouse
git push [remote] [branch]

2. Particular Requirement

2.1 Add a repository that only push, not fetch.

1
git remote set-url --add origin <your_repository_url>

3. Push an existing repository from the command line

1
2
3
git remote add origin https://github.com/moblackwhite/my-test.git
git branch -M main
git push -u origin main

Git common commands
https://www.hardyhu.cn/2022/01/15/Git-common-commands/
Author
John Doe
Posted on
January 15, 2022
Licensed under