Git:Example
lastmod 2024-04-02created 2018-06-2015 edits
Notes on the main Git commands and how to use them.
Config
-
git config --global --list - Shows the current settings. The --global option applies to the global settings; omit it to apply only to the current project.
-
git config --global user.name "사용자명" - Registers the user name. (Required)
-
git config --global user.email "이메일주소" - Registers the e-mail address. (Required)
-
git config --global color.ui auto - Shows colors in messages displayed in the terminal.
-
git -c user.name=사용자명 -c user.email=이메일주소 ... - Temporarily changes the user name and e-mail address.
Branch
-
git branch - Lists the existing branches. Use the -r option to see the branches of the remote repository.
-
git branch 브랜치명B 브랜치명A - Creates a new branch B from branch A. (In git, the default branch is named master.)
-
git branch 브랜치명 - Creates a new branch with the given name. (Does not check it out.)
-
git branch -d 브랜치명 - Deletes a branch.
-
git branch -m 존재하는브랜치명 새로운브랜치명 - Renames an existing branch to the new branch name. If a branch with that name already exists you get an error, but with the -M option it is overwritten even if the branch already exists.
-
git tag 태그명 브랜치명 - Attaches a tag with the given tag name to the current point of the branch. Entering just git tag shows the list of existing tags.
-
git checkout 브랜치명/태그명 - Switches the working tree to that branch or tag.
-
git checkout -b 브랜치명B 브랜치명A - Creates a new branch named B from branch A and checks it out.
-
git rebase 브랜치명 - Applies the changes of the given branch to the current branch.
-
git merge 브랜치명 - Merges the given branch into the current branch. With the --squash option, all commits of the given branch become a single commit.
-
git cherry-pick 커밋명 - Picks only the specific commit and makes it a commit on the current branch. With the -n option, it merges into the working tree but does not commit, so you can combine several commits into one commit.
Log
-
git log - Shows the commit logs; options like -1 or -2 set the number of commit logs to print. The --pretty=oneline option shows each on a single line, and you can set a format like --pretty=format:"%h %s". The -p option also shows the changes. Options such as --since="5 hours" or --before="5 hours" are also available. The --graph option shows the branch tree.
-
git log 커밋명
:Shows the log of the given commit. Entering commitA..commitB (two dots) shows the log from after commitA up to commitB. ^ is the same as -1, so HEAD^ is the commit right before the latest one; you can also write HEAD^^^, and HEAD~3 means the commit 3 before HEAD.
-
git blame 파일명 - Shows information such as the commit and the committer in front of each line.
-
git blame -L 10,15 파일명 - The -L option lets you view a range from line 10 to line 15, and you can use something like +5 instead of 15. A regular expression can also be used instead of a numeric range.
-
git blame -M 파일명 - The -M option finds repeated patterns to detect copied or moved content. The -C -C option finds copies between files. -C -C can also be used with git log, and to find copied content use the -p option with git log.
Reset/Revert
-
git revert 커밋명 - Creates a new commit that undoes the changes made in an existing commit. With the -n option it does not commit immediately, so you can revert several times and then commit. (Always revert starting from the most recent commit.)
-
git reset 커밋명 - Used to modify previous commits. The --soft option stages the previous commits without committing, and the --hard option removes the commits from the repository and the working tree. Entering git reset HEAD^ undoes the most recent commit.
-
git rebase -i 커밋범위 - With the -i option, you can reorder or combine commits in interactive mode.
-
git reset --hard HEAD - Reverts the entire working tree to the last commit. All changes in the working tree and index since the last commit are lost. (Useful if you have not committed the changes.)
-
git reset HEAD^ - Undoes the last commit. The working tree is preserved. (Useful when you committed but have not pushed.)
-
git reset HEAD~2 - Undoes the last 2 commits. The working tree is preserved.
-
git reset --hard HEAD~2 - Undoes the last 2 commits. Both the index and the working tree are restored.
-
git reset --hard ORIG_HEAD - When a merge has already been committed, undoes that commit. (Useful when a bad merge has already been committed.)
-
git revert HEAD - Creates a new commit that undoes the changes made in HEAD (undo commit). (Useful when the commit has already been pushed.)
Repository
-
git clone 저장소주소 폴더명 - Creates a repository by cloning a remote repository. The folder name can be omitted.
-
git fetch - Fetches changes from the remote repository and updates the remote branches.
-
git pull - Does in one step what git fetch does (getting changes from the remote repository) plus merging them into the local branch. You can pass the remote repository to pull from and the local branch to update as parameters.
-
git push - Without parameters, pushes to the origin repository, to the branch with the same name as the current local branch. The --dry-run option lets you check the changes that would be pushed. Tags added locally are not pushed by default, so you need git push origin tagname, or git push origin --tags to push all tags.
-
git remote add 이름 저장소주소 - Adds a new remote repository.
-
git remote - Lists the added remote repositories.
-
git remote show 이름 - Shows information about the given remote repository.
-
git remote rm 이름 - Removes a remote repository.
Submodule
-
git submodule - Shows the associated submodules.
-
git submodule add 저장소주소 서브모듈경로 - Adds a new submodule at the given path. It is only added, not initialized, and a minus (-) sign appears in front of the commit hash.
-
git submodule init 서브모듈경로 - Initializes the submodule.
-
git submodule update 서브모듈경로 - Applies the submodule's changes. (Does not track the latest commit of the repository.)
Archive
-
git archive --format=tar --prefix=폴더명/ 브랜치혹은태그 | gzip > 파일명.tar.gz - Compresses the given branch or tag as TAR. With --prefix, the archived files are created inside that folder.
-
git archive --format=zip --prefix=폴더명/ 브랜치혹은태그 > 파일명.zip - Compresses the given branch or tag as ZIP. With --prefix, the archived files are created inside that folder.
ETC
-
git mergetool - Finds and runs the merge tool set in the merge.tool setting.
-
git gc - Optimizes the repository's logs. The logs themselves do not change; only the way they are stored is optimized. The --aggressive option optimizes more thoroughly.
-
git rev-parse --show-toplevel - When entered inside a git repository, shows the root directory.
-
git fsck - Verifies whether the Repository has errors
-
git format-patch - Prepares an e-mail submission. (Linux kernel-style)
-
git am - Apply patches e-mailed in from your contributors.
-
git daemon - Lets anonymous users download the Repository.
-
git shell - can be used as a restricted login shell for shared central repository users.
Stash save/pop
To temporarily save to the Stash and restore it:
Remove Untracked files
Use the following command.
But beware... there's no going back. Use -n or --dry-run to preview the damage you'll do.
- If you want to also remove directories: run
git clean -f -d - If you just want to remove ignored files: run
git clean -f -X - If you want to remove ignored as well as non-ignored files: run
git clean -f -x
In short, to remove only ignored files and directories, enter git clean -dfX; to delete all untracked files, enter git clean -dfx.
Remove last commit
To undo the last commit:
Note that ^ means one step back. So HEAD^ means the commit right before the latest commit.
Revert modify content (Not staging area)
To revert files that were modified but not yet added to the staging area.
Revert modify content (Staging area)
To remove files that were modified and added to the staging area from the stage again.
Changing only the HEAD commit message
Changing commit messages before HEAD
To change messages up to the third one back
How to check the number of revisions
Git ZIP Export
After working with Git, sometimes you need only the pure source files without the git-related files. This is the old export feature; in git, use the following command.
This compresses and saves it as out.zip in that directory.
Disabling SSL verification
Either turn it off with a setting:
or use the environment variable GIT_SSL_NO_VERIFY=0.
Checking the CA certificate path
- How to fix SSL certificate errors when connecting to an https repository in git
- [curl.haxx.se/docs/sslcerts.html curl - SSL CA Certificates]
Viewing verbose logs
Revert
Usually, when you want to cancel the work of a specific Commit, rather than trying to delete the Commit with a Rebase, you create and append a new Commit that does the exact opposite of the Commit you want to cancel (Revert), which has the same effect as deleting the Commit. This makes the source code timeline somewhat messier, but it is a very small problem compared to the confusion caused by Commit IDs changing through a Rebase.
Resolving conflicts found during a rebase
After git pull or git fetch, the graph may split like this.
git log10a
* a05b178 (HEAD -> master) Fix: Error in assignment of synchronized values.
| * 78b286b (origin/master, origin/HEAD) Create main() funcion.
|/
* 5fde85e Update default values.
* 6e14891 (tag: 1.1.3) Update version: 1.1.3
* 52535e6 Handled the StopIteration exception.
* d96d377 (tag: 1.1.2) Update version: 1.1.2
* 84821f7 Create kill_process() method.
* 8c470ac (tag: 1.1.1) Update version: 1.1.1
* 3cb8450 Add prop: refresh_error_threshold
* 296782c Refactoring class constructors.
If a conflict occurs while running the rebase command to merge the graph, the following error is printed.
$ git rebase origin/master
First, rewinding head to replay your work on top of it...
Applying: Fix: Error in assignment of synchronized values.
Using index info to reconstruct a base tree...
M av_stream_video.app.py
M av_stream_video_server.py
Falling back to patching base and 3-way merge...
Auto-merging av_stream_video_server.py
CONFLICT (content): Merge conflict in av_stream_video_server.py
Auto-merging av_stream_video.app.py
error: Failed to merge in the changes.
Patch failed at 0001 Fix: Error in assignment of synchronized values.
hint: Use 'git am --show-current-patch' to see the failed patch
Resolve all conflicts manually, mark them as resolved with
"git add/rm <conflicted_files>", then run "git rebase --continue".
You can instead skip this commit: run "git rebase --skip".
To abort and get back to the state before "git rebase", run "git rebase --abort".
Checking the status prints the following.
$ git status
rebase in progress; onto 78b286b
You are currently rebasing branch 'master' on '78b286b'.
(fix conflicts and then run "git rebase --continue")
(use "git rebase --skip" to skip this patch)
(use "git rebase --abort" to check out the original branch)
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
modified: av_stream_video.app.py
Unmerged paths:
(use "git restore --staged <file>..." to unstage)
(use "git add <file>..." to mark resolution)
both modified: av_stream_video_server.py
To check the Unmerged paths item, running diff prints the following.
git diff
diff --cc av_stream_video_server.py
index b960b49,9287542..0000000
--- a/av_stream_video_server.py
+++ b/av_stream_video_server.py
@@@ -172,9 -188,9 +188,13 @@@ class StreamVideoServer
if not self.is_opened_video():
self.open_video()
- while not self.exit_flag.value:
+ while not self._get_exit_flag():
++<<<<<<< HEAD
+ if self.refresh_flag:
++=======
+ if self._get_refresh_flag():
++>>>>>>> Fix: Error in assignment of synchronized values.
print_out(f'StreamVideoServer.run() [REFRESH] -> Flag is is enabled.')
reconnect_result = self.reopen_video()
if reconnect_result:
Edit the file with vim, then add the file.
Check the status again.
git status
rebase in progress; onto 78b286b
You are currently rebasing branch 'master' on '78b286b'.
(all conflicts fixed: run "git rebase --continue")
Changes to be committed:
(use "git restore --staged <file>..." to unstage)
modified: av_stream_video.app.py
modified: av_stream_video_server.py
To finish the rebase, enter what is written above:
Checking the status shows that 1 commit has been completed.
git status
On branch master
Your branch is ahead of 'origin/master' by 1 commit.
(use "git push" to publish your local commits)
nothing to commit, working tree clean
Checking the graph shows it has been merged cleanly, as follows.
git log10a
* b202582 (HEAD -> master) Fix: Error in assignment of synchronized values.
* 78b286b (origin/master, origin/HEAD) Create main() funcion.
* 5fde85e Update default values.
* 6e14891 (tag: 1.1.3) Update version: 1.1.3
* 52535e6 Handled the StopIteration exception.
* d96d377 (tag: 1.1.2) Update version: 1.1.2
* 84821f7 Create kill_process() method.
* 8c470ac (tag: 1.1.1) Update version: 1.1.1
* 3cb8450 Add prop: refresh_error_threshold
* 296782c Refactoring class constructors.
Tips
See the link above for the following:
- Using Git with about 20 commands
- View the helpful guides that come with Git
- Search changes by content
- Sync with remote and overwrite local changes
- List all files up to a specific commit
- Reset the first commit
- List all conflicted files
- List all files changed in a specific commit
- View unstaged changes since the last commit
- View changes staged for commit
- View both staged and unstaged changes
- List all branches already merged into the master branch
- Switch to the previous branch
- Delete all branches already merged into the master branch
- List all branches with their upstreams and last commits
- Set the upstream branch (tracking)
- Delete a local branch
- Delete a remote branch
- Delete a local tag
- Delete a remote tag
- Revert local changes to the last content of head
- Revert: undo a commit by creating a new commit
- Reset: remove commits (recommended only on private branches)
- Change the previous commit message
- View the history of commits on a branch that have not been merged upstream
- Amend the Author
- Reset the author to the author changed in the global config
- Change a remote URL
- List all remote references
- List all local and remote branches
- List only remote branches
- Stage only part of a file's changes, not all of them
- Use git bash completion
- View changes from 2 weeks ago until now
- View all commits made since forking from master
- Bring commits across branches using cherry-pick
- Find branches that contain a given commit hash
- Set Git command aliases
- Save the state of uncommitted tracked files
- Save the current state of unstaged changes to tracked files
- Save the current state including untracked files
- Save the current state with a message
- Save the current state of all ignored, untracked, and tracked files
- List all saved stashes
- Apply a stash without deleting it from the stash list
- Apply the last saved stash state and delete it from the stash list
- Delete all saved stashes
- Get a single file from a stash
- Show all tracked files
- Show all untracked files
- Show all ignored files
- Create a new working tree in a repository (git 2.5)
- Create a new working tree from HEAD
- Untrack files without deleting them
- Before actually deleting untracked files/directories, test which files/directories would be deleted
- Forcefully delete untracked files
- Forcefully delete untracked directories
- Update all submodules
- View all commits on the current branch not yet merged into master
- Rename a branch
- Rebase the 'feature' branch onto master and then merge it into master
- Archive the master branch
- Change the previous commit without changing the commit message
- Remove references to remote branches deleted on the remote
- Get the commit hash of the first revision
- Visualize the version tree
- Deploy a tracked subfolder to the gh-pages branch
- Add a project to a repository using subtree
- Get the latest changes of a linked project into the repository using subtree
- Export a branch with its history to a file
- Import a bundle
- Get the current branch name
- Ignore a file when committing (e.g., a Changelog file)
- Stash changes before rebasing
- Fetch a pull request by ID into the local repository
- Show the most recent tag on the current branch
- View diff by word
- View changes using a diff tool
- Ignore changes to a tracked file
- Undo assume-unchanged
- Delete the files listed in .gitignore
- Restore a deleted file
- Restore a file to a specific commit
- Always rebase instead of merging on pull
- List all aliases and config values
- Enable case sensitivity
- Add a custom editor
- Enable automatic typo correction
- Check which release a change belongs to
- Test a command (works with any command that supports the dry-run flag)
- Mark a commit as a fix of a previous commit
- Squash fixup commits into normal commits
- Skip staging files when committing
- Stage interactively
- List ignored files
- Print the status of ignored files
- List commits that are in Branch1 but not in Branch2
- List the last n commits
- Record and reuse how previous conflicts were resolved
- Open all conflicted files in an editor
- Show the number of unpacked objects and their disk usage
- Remove unreachable objects from the object database
- Browse the working directory with gitweb
- Show GPG signatures in the commit log
- Remove an entry from the global config
- Check out a new branch with no history
- Get file contents from another branch
- List only root commits and merge commits
- Change the previous two commits with an interactive rebase
- List all branches being worked on
- Find good/bad commits with binary search
- Bypass the pre-commit and commit-msg git hooks
- List commits and changes for a specific file (also tracks renamed files)
- Clone a single branch
- Create a new branch and switch to it at the same time
- Ignore file mode changes when committing
- Disable Git terminal color output
- Set color settings for specific commands
- List all local branches sorted by most recent commit date
- Search tracked files for lines matching a pattern (regular expression or string)
- Clone a shallow copy of a repository
- Search commit logs across all branches for the given text
- Get the first commit of a branch (started from the master branch)
- Unstage staged files
- Force push to a remote repository
- Add a repository name
- Show the author, time, and last revision for each line of a given file
- Group commits by Author and title
- Force push without overwriting other people's work
- Show the number of lines contributed by a specific author
- Revert: revert a merge
- Print the number of commits on a specific branch
- Alias: git undo
- Add notes (memos) to objects
- Show all git notes
- Apply a commit from another repository
- Specify a fetch reference
- Find the common ancestor commit of two branches
- List unpushed commits
- Add all changes except whitespace changes
- Edit the git config [local/global]
- Show blame information for a specific range
- Show Git logical variables
- Pre-format a patch file
- Get the repository name
- Print commit logs between specific dates
- Exclude an author from the log
- Summarize a branch's changes
- List all references in a remote repository
- Back up untracked files
- List all git command aliases
- Show a short git status
- Check out the commit from a day ago
- Push a new local branch to the remote repository and track it
- Change a branch's base
- Use SSH instead of HTTPs for remote repositories
- Update a submodule to the latest commit
- Prevent automatic conversion from LF to CRLF