The source code for this blog is available on GitHub.
Note
Top

Git - Command line tool

Cover Image for Git - Command line tool
Chen Han
Chen Han

Git

Git is a version control system that helps developers track and manage changes to their codebase. It allows developers to collaborate on projects, experiment with new ideas, and revert back to previous versions of the code if necessary.

Here are some key concepts in Git:

  • Repositories: A repository (or "repo") is a collection of files and the history of changes to those files. A repository can be local (stored on your computer) or remote (stored on a server).
  • Commits: A commit is a snapshot of the repository at a specific point in time. When you make a change to a file and save it, you create a new commit that records the changes you made. Each commit has a unique identifier (called a "sha"), a message that describes the changes made in the commit, and the name of the person who made the commit.
  • Branches: A branch is a separate line of development within a repository. By default, a repository has a single branch called "master". You can create new branches to work on new features or fix bugs, and then merge the changes back into the master branch when you are ready to release them.
  • Merging: Merging is the process of combining changes from different branches. When you merge two branches, Git compares the changes made in each branch and attempts to automatically merge them together. If there are conflicts (e.g., two people changed the same line of code in different ways), you may need to resolve the conflicts manually.

These are just a few of the basics of Git. There are many more features and concepts to learn, such as staging changes, pushing and pulling from remote repositories, and using Git for collaboration and version control. I hope this gives you a good starting point for learning more about Git!

iTerm (mac only), shortcut, and simple command

iTerm is a terminal emulator for macOS that provides a feature-rich interface for working with command-line tools and utilities. Some of the core concepts of iTerm include:

  • Windows: A window in iTerm refers to an instance of the application. Each window can have multiple tabs, allowing you to work with multiple terminal sessions at the same time.
  • Tabs: A tab in iTerm is a single terminal session. Each tab can have multiple panes, allowing you to split a single tab into multiple "views" of the terminal.
  • Panes: A pane in iTerm is a single "view" of the terminal. You can split a tab into multiple panes, allowing you to work with multiple terminal sessions within a single tab.
  • Profiles: A profile in iTerm is a set of settings that determine how the terminal will behave. Each tab or pane can have its own profile, allowing you to customize the settings for each session.
  • Triggers: A trigger in iTerm is a way to automatically perform an action when certain text is output to the terminal. Triggers can be used to run scripts, send notifications, or perform other actions.
  • Hotkeys: iTerm provides a wide range of hotkeys for quickly navigating and working with the terminal. For example, you can use hotkeys to switch between tabs, panes, and windows, or to quickly access the command history.

How can i open a new pane and toggle from current pane to another pane

In iTerm, you can open a new pane by using the keyboard shortcut command + d. This will split the current window into two panes, with the new pane appearing to the right of the current one. You can also use the command + shift + d shortcut to split the current window into two panes, with the new pane appearing below the current one. Additionally, you can use the View > Split Pane Horizontally or View > Split Pane Vertically menu options to open a new pane.

Once you have multiple panes open, you can toggle between them using the following keyboard shortcut:

  • To switch to the next pane: press Cmd + ]
  • To switch to the previous pane: press Cmd + [

Rename folder

To rename a folder in the command line, you can use the following command:

mv old-folder-name new-folder-name

This will rename the folder old-folder-name to new-folder-name. Replace old-folder-name and new-folder-name with the actual names of the folder you want to rename.

Note: Make sure to run this command from the directory that contains the folder you want to rename.

How to uninstall specific package

To uninstall a specific package in npm, you can use the following command:

npm uninstall package-name

Replace package-name with the name of the package you want to uninstall.

For example, to uninstall the lodash package, you would run the following command:

npm uninstall lodash

This will remove the package from your project and also remove it from the dependencies section in your package.json file.

Note: Before uninstalling a package, make sure that it is not required by any other packages in your project, otherwise, it may cause errors or unexpected behavior.

Basic Usage

Git is a powerful tool that allows developers to track and manage changes to their codebase. To use Git, you will first need to initialize a repository by running the git init command. This creates a .git folder in your current directory, which stores the Git metadata and history of your repository. You can then use the git add command to stage changes to your files, and the git commit command to save a snapshot of your repository with a descriptive message. You can use the git log command to view the history of commits, and the git checkout command to switch between branches. These are just a few of the basic commands in Git, and there are many more features and options to explore as you learn more about version control with Git.

How to install Git on your computer

To install Git on your computer, you can follow these steps:

  1. Go to the Git website (https://git-scm.com/downloads) and choose the version that is appropriate for your operating system.
  2. Click on the download link to download the Git installer.
  3. Once the download is complete, open the installer and follow the prompts to install Git on your computer. This typically involves accepting the terms of service, selecting the destination folder for the installation, and choosing the components to install.
  4. Once the installation is complete, you can open a terminal or command prompt and type git --version to verify that Git has been installed successfully.

That's it! You should now have Git installed on your computer and be ready to start using it for version control. If you encounter any issues or errors during the installation process, you can consult the Git documentation or seek help from the Git community.

Initializing and Checking the Status of a Git Repository

Git is a powerful tool that allows you to track and manage changes to your codebase. When you're starting a new project, the first thing you'll need to do is initialize a Git repository. To do this, you can use the git init command. This command creates a new .git folder in your current directory, which stores the Git metadata and history of your repository. Now that you've initialized your repository, you can start using Git to track changes to your code.

To see the status of your repository, you can use the git status command. This command will show you which files have been modified, added, or deleted since your last commit. The modified files are shown in red, which means they are "unstaged." This means that Git is aware that these files have been modified, but they are not yet part of the repository. The added files are shown in green, which means they are "staged." This means that these files have been added to the repository and will be included in the next commit. You can use the git add command to stage files, and the git commit command to save a snapshot of your repository with a descriptive message.

git init
git status

Committing Changes to a Git Repository

Git allows you to save snapshots of your repository at different points in time. These snapshots are called "commits," and they are used to track the changes you make to your codebase.

To commit changes to your repository, you can follow these steps:

  1. Stage the files you want to include in your commit. This can be done using the git add command. For example:
git add . # stages all unstaged files
git add a.txt b.txt # stages specific files
  1. Commit the staged files with a descriptive message. This can be done using the git commit command. For example:
git commit -m "feat: development changes" # commits all staged files
git commit -am "feat: development changes" # commits all staged and unstaged files

If you want to combine new changes with an old commit, you can use the git commit --amend command. This command allows you to update the previous commit with your new changes. For example:

git add . # stages all unstaged files
git commit --amend --no-edit # combines new changes with old commit
git commit --amend -a --no-edit # combines new changes with old commit, including unstaged files

Viewing Commits

To view the commits in your repository, you can use the git log command. By default, this will show you a list of commits with their SHA, author, date, and commit message. You can use the --one-line flag to show a condensed version of the log:

git log --one-line

To exit the log view, you can press q.

Customize the output of git log

To view the commit history of a repository, you can use the git log command. This command shows the commit history in a chronological order, with the most recent commit at the top. By default, the git log command shows the commit hash, author, date, and commit message.

You can customize the output of the git log command by using options such as --oneline, --graph, --author, and --since.

For example, to show the commit history in a single line with the commit hash and commit message, you can use the --oneline option:

git log --oneline

To show the commit history as a graph, you can use the --graph option:

git log --graph

To filter the commit history by author, you can use the --author option:

git log --author=<author name>

To filter the commit history by a specific time period, you can use the --since option:

git log --since=<time period>

For example, to show the commit history for the past week, you can use the following command:

git log --since=1.week

View the differences between commits

To view the differences between two commits, you can use the git diff command. This command shows the changes

How to reset untracked files

git status                                                                                      128 ↵
On branch HY-22-TypeScript
Your branch is up to date with &#39;origin/HY-22-TypeScript&#39;.

Changes to be committed:
  (use &quot;git restore --staged &lt;file&gt;...&quot; to unstage)
        deleted:    next.config.js

Untracked files:
  (use &quot;git add &lt;file&gt;...&quot; to include in what will be committed)
        next-env.d.ts
        tsconfig.json

To reset untracked files in Git, you can use the following command:

git clean -f

This command will remove all untracked files and directories in your Git repository. The -f option is used to force the removal of files.

If you want to preview the files that will be removed without actually removing them, you can use the -n option instead:

git clean -n

It's important to note that using git clean is a destructive operation and cannot be undone, so make sure to backup your project before using this command.

Switching Branches

To switch between branches in your repository, you can use the git checkout command followed by the name of the branch. For example:

git checkout feat/some-func

If you want to create a new branch, you can use the -b flag:

git checkout -b feat/new-branch

For more information on working with branches in Git, you can refer to this link

Renaming a Git Branch

Renaming a local branch is easy. You just need to use the git branch command with the -m flag and specify the old name and the new name. For example:

git branch -m <old_name> <new_name>

If you also want to rename the remote branch, you'll need to do a few extra steps. First, delete the old branch on the remote. You can do this with either of the following commands:

# Delete the old branch on remote - where <remote> is, for example, origin
git push <remote> --delete <old_name>

# Or shorter way to delete remote branch [:]
git push <remote> :<old_name>

Then, push the new branch to the remote:

git push <remote> <new_name>

For example:

# delete old branch
$ git push origin --delete han/playground
 - [deleted]         han/playground

Ignoring Files with .gitignore

The .gitignore file is used to tell Git which files or directories should be ignored. This is useful when you have certain files or directories that you don't want to track, such as build artifacts or temporary files.

Here's an example .gitignore file that ignores all files in the src/renderer/assets/images directory, except for the index and default directories:

# images everything, but not index, default directories
src/renderer/assets/images
!src/renderer/assets/images/index
!src/renderer/assets/images/default

For more information on how to use the .gitignore file, check out this StackOverflow question.

Using GitHub

To use GitHub, you'll need to set up an SSH key on your computer. This will allow you to securely connect to GitHub and push and pull changes to your repositories.

  1. Go to your GitHub settings and click on the "SSH and GPG keys" tab.
  2. Generate a new key on your local machine by running the following command:
ssh-keygen -t rsa
  1. Copy the key that was generated (located in ~/.ssh/id_rsa.pub) and paste it into the "Key" field on the GitHub page.
  2. Click the "Add SSH key" button.

To create a new repository on GitHub, click the "New" button on your repositories page. Give your repository a name and a brief description, then click the "Create repository" button.

After creating a new repository, you'll be given detailed instructions on how to push your code to GitHub. Follow these instructions to set up your local repository and push your code to the remote repository.

How to use command line to see the conflict files

git diff --name-only --diff-filter=U

There are several command line tools that can be used to see the conflict files in a version control system like Git. Here are a couple of examples:

  1. git diff: This command can be used to see the differences between the files in the working directory, the staging area, and the last commit. It can also be used to show the conflicts between branches or commits. For example, if you are trying to merge a branch and there are conflicts, you can use git diff to see the conflicting lines in the files.
  2. git status: This command can be used to see the current state of the working directory, including which files have changes that have not been committed. It can also be used to show which files have conflicts in case of merging, you can use git status to see the files with conflicts,
  3. git diff --name-only --diff-filter=U: This command can be used to list the name of the conflicted file, only showing conflicts, this command list all the conflicted files, and nothing else.

These are just a few examples of the command line tools that can be used to see the conflict files in a version control system like Git. There are many other options and commands that can be used depending on your specific needs and use case.

Fetching Changes from a Remote Repository

To get the latest changes from a remote repository, you can use the git fetch command. This will download any new branches and commits from the remote.

If you want to switch to a remote branch that exists on a remote repository, but not on your local machine, you can use the git fetch command to retrieve the latest version of the branch, and then use either git checkout -b <branch-name> origin/<branch-name> or git checkout -t origin/<branch-name> to switch to the branch.

Here's an example:

# Retrieve the latest version of the remote branch
git fetch

# Switch to the remote branch
git checkout -b member-order origin/member-order

# Or alternatively
git checkout -t origin/member-order

For more information, you can refer to this Stack Overflow thread: How do I check out a remote Git branch?

Syncing with a Remote Repository

Sometimes, you may find that your local repository differs from a remote repository, such as a repository on GitHub. In such cases, you may want to sync your local repository with the remote repository to ensure that you have the most up-to-date code.

Pulling Changes from a Remote Repository

The git pull command is used to fetch and download content from a remote repository and immediately update the local repository to match that content.

To pull changes from a remote repository, you can use the following command:

git pull

This will fetch the latest changes from the remote repository and merge them into your local repository.

Pushing Changes to a Remote Repository

The git push command is used to upload local repository content to a remote repository.

To push changes to a remote repository, you can use the following command:

git push

This will upload your local changes to the remote repository.

Syncing a Forked Repository

If you have forked a repository and want to sync your fork with the upstream repository (the repository that you forked), you can use the following steps:

  1. Add the upstream repository as a remote:
git remote add upstream https://github.com/upstream/repository.git
  1. Fetch the latest changes from the upstream repository:
git fetch upstream
  1. Check out your local master branch:
git checkout master
  1. Merge the changes from the upstream repository into your local master branch:
git merge upstream/master
  1. Push the updated master branch to your fork on GitHub:
git push origin master

Ignoring Files

Git allows you to specify a list of files that you want to ignore, meaning that Git will not track changes to those files. This is useful for ignoring temporary or log files that you don't want to commit to your repository.

To ignore a file, you can add its name or a pattern matching its name to a .gitignore file in the root directory of your repository. For example:

# Ignore all files in the images directory
src/renderer/assets/images

# Except for the index and default directories
!src/renderer/assets/images/index
!src/renderer/assets/images/default

Using GitHub - Setting Up SSH Keys

To use Git with a remote repository, such as one hosted on GitHub, you will need to set up an SSH key for your computer.

To generate an SSH key, you can use the following command:

ssh-keygen -t rsa

Then, copy the generated key to your GitHub account by going to the "SSH and GPG keys" settings page and adding a new key.

The following markdown file provides information on how to make changes to remote branches in Git.

Add a remote branch

To add a new remote branch to your local repository, you can use the following command:

git remote add origin git@github.com:ibizatw/tungrp-backend.git

This will add a new remote branch called "origin" to your local repository, which is located at the specified URL (in this case, git@github.com:ibizatw/tungrp-backend.git).

Change the name of a remote branch

If you want to change the name of an existing remote branch, you can use the following command:

git remote set-url origin https://github.com/kurtsgm/liteshop.git

This will change the name of the "origin" remote branch to the specified URL (in this case, https://github.com/kurtsgm/liteshop.git).

Merge the latest changes into the latest commit

To merge the latest changes from your local repository into the latest commit, you can use the following command:

git commit --amend -m "Welcome To Facebook"

This will update the latest commit with the latest changes from your local repository, and add the message "Welcome To Facebook" to the commit.

Change the name of a branch

If you want to change the name of a branch, you can use the following command:

# Change the local branch name
git branch -m member-order
# Update the remote branch name: push the new_name local branch and reset the upstream branch
git push origin -u member-order
# Delete the old branch
git push origin --delete feat/docker-environment

This will change the name of the local branch to "member-order", update the name of the corresponding remote branch to "member-order", and delete the old branch "feat/docker-environment".

For more information, you can refer to this link to see more

Restore to a certain state

# View the commit to be restored
git reflog
# Perform the restore
git reset --hard <your commit>

Reset a file

I want to reset yarn.lock

git checkout HEAD -- yarn.lock

cherrypick

Bring a single point over

git cherry-pick ca236956e

Bring multiple points over ➡️ If you have selective revisions to merge, say A, C, F, J from A,B,C,D,E,F,G,H,I,J commits, simply use the below command:

git cherry-pick A C F J

Sometimes you may be asked to use the following command. This is because before executing pick, the modified things are already on the branch (maybe a colleague has already modified it, or it has been modified during a conflict resolution, etc.).

git commit --allow-empty

I want to use keyword to pinpoint the actual branch I want to go

To use a keyword to search for a specific branch in Git, you can use the git branch command with the -a option to list all branches (local and remote), and then use the grep command to search for a specific keyword. For example:

git branch -a | grep <keyword>

This will list all branches that contain the specified keyword in their name. You can then use the git checkout command to switch to the desired branch, like this:

git checkout <branch-name>

Alternatively, if you only want to search for local branches, you can omit the -a option from the git branch command, like this:

git branch | grep <keyword>

This will only search for local branches that contain the specified keyword in their name.

I want to delete remote locally

To delete a remote repository on your local machine, you can use the Git command line. Here are the steps:

  1. Use the git remote command to view a list of all the remote repositories currently configured on your local machine: git remote -v
  2. Use the git remote remove command to remove the remote repository that you want to delete: git remote remove <remote_name>
  3. Verify that the remote repository has been removed by running the git remote -v command again. The remote repository should no longer be listed.

It's important to note that this will only delete the reference to the remote repository on your local machine, it will not delete the actual remote repository on the hosting service (e.g. GitHub, GitLab, etc.).

You should also be aware that deleting a remote repository will also delete all the branches, tags and commits which are related to that remote repository on your local machine.

I want to search lastest 10 branch on git

You can use the git branch command with the -r option to list all the remote branches and then use the -n option to limit the number of branches displayed.

git branch --sort=-committerdate | head -n 10     # local repo
git branch -r --sort=-committerdate | head -n 10  # remote repo 

This command will list the 10 most recent branches on the remote repository.

How to delete remote branch

To delete a remote branch, you can use the git push command with the --delete flag. Here are the steps:

  1. Use the git branch -r command to list all the branches on the remote repository.
  2. Use the git push command to delete the branch from the remote repository. The syntax is as follow: git push <remote> --delete <branch>

For example, to delete a branch named "feature1" from the remote repository named "origin", you would run the following command:

git push origin --delete 278-fix-miscellaneous-issues  

You can also use -d instead of --delete in the above command.

Alternatively, you can also use git branch -r -d origin/<branch> to delete the remote branch.

It's worth mentioning that after you delete a remote branch, it will also be deleted from your local repository the next time you run git fetch or git pull.

Please be careful when deleting remote branches, because it can cause loss of data, especially if other team members are working on the same branch.

Search keyword from previous commits

I want to upgrade the Next and React versions. Unfortunately, I lost the credit, so I need to upgrade them after I earn the credit back and Tom begins to believe me. That's why I want to find the previous commit so that I can restore my reverted changes seamlessly.

You can use the git log command with the --grep option to search for a keyword in commit messages. This will display a list of all the commits that contain the specified keyword in their commit messages.

git log --all --grep=&quot;upgrade&quot;
git log --grep=&quot;upgrade&quot; --pretty=oneline

Advanced features

The following markdown file provides some advanced Git functions, including how to view deleted files, how to delete files, how to revert a pull request (PR) on GitHub, and how to apply changes from one branch to another using git diff and git apply. It also mentions using a graphical user interface (GUI) to view a log of Git commits.

Viewing Deleted Files

To view deleted files, you can use the following commands:

# Find deleted files (to find the file name)
git log --diff-filter=D --summary | grep delete
# Find the most recent commit that deleted the file (to find the commit)
git rev-list -n 1 HEAD -- app/services/order/rebate.rb
# Restore the deleted file
# usage: git checkout <commit code>^ -- file path
git checkout f5edc1689daf6f19121941a94e5e041e5a4bb03b^ -- app/services/order/rebate.rb

Deleting a File

To delete a file, you can use the following command:

git checkout HEAD -- webpack.config.js

Reverting a Pull Request on GitHub

If a pull request has already been merged, you can use the "Revert" function to restore it.

Applying Changes from One Branch to Another

To apply changes from one branch to another, you can follow these steps:

  • Generate a diff file
  • Use diff to apply the changes

For example:

# Generate a diff file
git diff > tun.diff
# Apply the changes
git apply my.diff
# Check for any issues
git diff
# If there are no issues, create a new commit

Using a Git GUI

To view a log of Git commits in a GUI, you can use the following command:

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

Links for reference: 痞客邦, drifting ruby

Git GUI

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

Pretty

Command Interpretation
--pretty=format:"%h%x09%an%x09%ad%x09%s" Hash+author+date+subject
--pretty=format:'%ad%x08%aN' Date+author
--pretty=format:"%H %an %ad" Hash+author+date
--pretty=format:"%H %an %ad" --date=short Hash+author+date (short)
--pretty="%C(Yellow)%h %C(reset)%ad (%C(Green)%cr%C(reset))%x09 %C(Cyan)%an: %C(reset)%s" -7 1. Hash+date+author+content
2. Last 7 commit

To shorten the date (not showing the time), use --date=short.

In case you were curious about the different options: %h = abbreviated commit hash %x09 = tab (character for code 9) %an = author name %ad = author date (format respects --date= option) %s = subject

img

Command Line GUI

$ git log --graph --all --decorate

Imgur

GitHub Policy Changes in 2021

remote: Support for password authentication was removed on August 13, 2021. Please use a personal access token instead.
remote: Please see https://github.blog/2020-12-15-token-authentication-requirements-for-git-operations/ for more information.
fatal: 無法存取 &#39;https://github.com/ibizatw/tungrp-backend.git/&#39;:The requested URL returned error: 403

Solution:

GitHub removed support for password authentication on August 13, 2021. To access your repository, you need to use a personal access token instead. Follow these steps to generate and use a personal access token:

  1. From your GitHub account, go to Settings => Developer Settings => Personal Access Token.
  2. Click Generate New Token and enter your password when prompted.
  3. Fill out the form to specify the permissions you want to grant to the token.
  4. Click Generate Token to create the token.
  5. Copy the generated token, which will be a long string of letters and numbers like ghp_sFhFsSHhTzMDreGRLjmks4Tzuzgthdvfsrta.

To edit or delete an existing entry for github.com in Keychain Access on macOS:

  1. Click on the Spotlight icon (magnifying glass) on the right side of the menu bar.
  2. Type Keychain Access and press the Enter key to launch the app.
  3. In Keychain Access, search for github.com.
  4. Find the internet password entry for github.com.
  5. Edit or delete the entry as needed.

Restore a Single (or Multiple) File from a Specific Commit

To restore the file campaign.jsx to the state it was in before the last two commits, use the following command:

git checkout 6192cd50d~2 -- app/javascript/bundles/admin/campaign/campaign.jsx

To restore multiple files, use a similar command:

git checkout 6192cd50d~2 -- app/javascript/bundles/admin/campaign/campaign.jsx

Filter

To view git log using filters such as date, author, etc., you can use the following commands:

Filter item Command
Date git log --after="2022-05-31" --until="2022-06-01"
Author git log --author=andy --date=iso
Date+author git log --after="2022-05-31" --until="2022-06-01" --author=andy --date=iso

Reference

© 2024 WOOTHINK. All Rights Reserved.
Site MapTerms and ConditionsPrivacy PolicyCookie Policy