Foundation
If you want to learn Git by reading just one chapter, then this is the one for you. This chapter covers the basic commands you'll use to do a variety of things with Git. By the end of this chapter, you should be able to configure and initialize a repository, start and stop tracking files, and stage or commit changes. This chapter will also show you how to configure Git to ignore specified files and file patterns, how to quickly and easily undo errors, how to browse your project's history and the differences between commits, how to push to your remote repository, and how to pull files from your remote repository.
Getting a Git Repositoryโ
There are generally two ways to get a Git project repository.
- convert a local directory that is not already version-controlled into a Git repository.
- clone an existing Git repository from another server.
Initializing a repository in a directoryโ
// Initialize the repository in the current directory
git init
This command will create a subdirectory called .git that contains all of the required files in the Git repository you are initializing, which are the backbone of the Git repository.
Cloning an Existing Repositoryโ
If you want to get a copy of an existing Git repository, for example, if you want to contribute to an open source project, you'll use the git clone command.
// Clone a remote repository
git clone <url>
If you want to customise the name of your local repository when you clone the remote repository, you can specify the new directory name with the additional parameter
// Specify the local naming of the repository
git clone <url> <name>
Cloning an existing repository is actually a breakdown of multiple commands. First initialize a local repository, then add a remote repository, and finally pull the remote repository data locally.
Log each update to the repositoryโ
Once we successfully have a repository, we can run git status when the repository status is available. In the absence of development, the repository is clean. When we have made changes to files in the working directory, every file in the working directory at that point has no more than these two statuses.
- tracked: these are files that are included in version control, have a record of them in the last snapshot and, after working on them for some time, their status may be unmodified, modified or in the staging area. In short, a tracked file is a file that Git already knows about.
- Untracked: All files in your working directory other than tracked files are untracked files, and are neither in the last snapshot nor in the staging area.
Running git status will show us which files we have changed, those that are tracked and those that are untracked. We can then add the files to the staging area using git add. Once added to the staging area, you can commit the update or continue working on it; if you continue working on it and make changes to the staged file, you can use git diff to see the difference between the file's workspace and the staging area.
If you commit a newly modified file to the staging area, the file in the staging area will be overwritten by the new commit. Once you have completed all your work and committed to the staging area, run git commit to the git directory to record this snapshot.
If you want to review your commit history after you've done multiple builds, you can use git log to view your commit history.
Ignoring Filesโ
Some files don't need to be managed by Git, and you don't want them to always appear in the untracked files list. In this case, we can create a file called .gitignore that lists the pattern of files to ignore. Different directories can have different .gitignore's.
The format of the file .gitignore is standardised as follows.
- All empty lines or lines starting with # will be ignored by Git.
- You can match using the standard glob pattern, which is applied recursively to the entire workspace (a glob pattern is a simplified regular expression used by the shell).
- Match patterns can begin with a (/) to prevent recursion.
- Match patterns can end in (/) to specify a directory.
- To ignore files or directories other than the specified pattern, the pattern can be prefixed with an exclamation mark (!) to reverse it.
GitHub has a very detailed list of .gitignore files for dozens of projects and languages, which you can find at https://github.com/github/gitignore.
Checking the current repository statusโ
// Check the current repository status at a glance
git status
// See a brief overview of the current repository status
git status -s
git status --short
// See the specific differences between the current file and the staging area
git diff
// The exact difference between the staging area and the last commit
git diff --staged
git diff --cached
Track new files or staging modified filesโ
// Add files to the staging area
git add <file>
// Add a path to the staging area
git add <path>
Commit the updateโ
// Committing the update will also start a text editor to type the commit instructions.
git commit
// Put the commit message on the same line as the command
git commit -m <msg>
// Skip the staging and commit the tracked file directly.
git commit -a
View commit historyโ
Common options for git logโ
// Format a line of output to show the commit history
git log --oneline
Options | Description |
---|---|
-p | Displays the differences introduced by each commit in patch format. |
--stat | Show file modification statistics for each commit. |
--shortstat | Show only the last line modification add remove statistics in --stat. |
--name-only | Show only the list of files modified after the commit message. |
--name-status | Displays a list of files added, modified and deleted. |
--abbrev-commit | Show only the first few characters of all 40 characters of the SHA-1 checksum. |
--relative-date | Display the date using a shorter relative time rather than the full format (e.g. "2 weeks ago"). |
--graph | Displays branch and merge history as an ASCII graph next to the log. |
--pretty | Display the history of commits in another format. Options available include oneline, short, full, fuller and format (to define your own format). |
--oneline | --pretty=oneline --abbrev-commit A suitable shorthand. |
git log --pretty=format Common optionsโ
// format allows you to customize the format in which logs are displayed
git log --pretty=format:"%h - %an, %ar : %s"
options | description |
---|---|
%H | The full hash of the commit |
%h | The abbreviated hash of the commit |
%T | The full hash of the tree |
%t | The abbreviated hash of the tree |
%P | The full hash of the parent commit |
%p | The short form hash of the parent commit |
%an | Author's name |
%ae | the author's email address |
%ad | The author's revision date (you can customize the format with the --date= option) |
%ar | Author revision date, by how long ago |
%cn | Submitter's name |
%ce | Submitter's email address |
%cd | Date of submission |
%cr | Date of submission (how long ago) |
%s | commit description |
Options for limiting git log outputโ
options | description |
---|---|
-n | Show only the n most recent commits. |
--since, --after | Show only commits after the specified time. |
--until, --before | Show only commits before the specified time. |
--author | Show only commits where the author matches the specified string. |
--committer | Show only commits where the submitter matches the specified string. |
--grep | Show only commits with the specified string in the commit description. |
-S | Show only commits with the specified string in the add or delete description. |
Undo operationsโ
Sometimes we find out after a commit that we have missed a few files, or that we have written the commit message incorrectly. In this case, you can run the commit command with the --amend option command with the --amend option to resubmit.
// Undo the last commit
git commit --amend
This command will commit the files in the current staging area together, and only one commit will end up - the second commit will replace the result of the first one.
Undoing a staged fileโ
// Undo the staging area file
git reset HEAD <file>
git reset is indeed a dangerous command, especially if you add the --hard option. In the above scenario, however, the files in the working directory have not yet been modified, so it is relatively safe.
Undoing changes to a fileโ
// Undo file changes in the workspace
git checkout -- <file>
Always remember that `git checkout -- <file>
is a dangerous command. Any changes you make to that file locally will disappear -- Git will overwrite it with the most recent commit. Don't use this command unless you really know you don't want to make local changes to that file.
Remote Repositoriesโ
To be able to collaborate on any Git project, you need to know how to manage your own remote repositories. A remote repository is a repository of your project hosted on the Internet or another network. of your project.
You can have several remote repositories, usually some are read-only to you and some are read-write. Collaborating with others involves managing remote repositories and pushing or pulling data as needed. Managing remote repositories includes understanding how to add remote repositories, remove invalid remote repositories, manage different remote branches and define whether they are tracked, etc.
Viewing remote repositoriesโ
You can run the git remote command to see the remote repository servers you have configured.
// View the remote repository
git remote
You can also specify the -v option, which will show you the URL of the Git repository that you need to read and write to, along with the abbreviation of the Git save
// Show the remote repository abbreviations and their URLs
git remote -v
Adding a remote repositoryโ
You can add a new remote Git repository by running git remote add <shortname> <url>` and specifying a convenient shorthand:
// Add a new remote Git repository
git remote add <remote-name> <url>
Grabbing and pulling from a remote repositoryโ
When you add a remote repository, you can pull data from the remote repository.
// Pulling data from a remote repository, without automatic merging.
git fetch <remote-name>
// Grab data from a remote repository and try to automatically merge it into the current branch.
git pull
Push to a remote repositoryโ
When you want to share your project, you must push it upstream.
// Push a branch to a remote repository
git push <remote> <branch>
Viewing, renaming and removing remote repositoriesโ
You can use the following commands to view, rename and remove remote repositories.
// To view a remote repository
git remote show <remote>
// Rename a remote repository
git remote rename <old> <new>
// Remove a remote repository
git remote remove <name>
Taggingโ
Git can tag a commit in the repository history to indicate its importance. It's typical for people to use this to tag release nodes (v1.0, v2.0, etc.)
Git supports two types of tags: lightweight tags and annotated tags.
A lightweight tag is much like a branch that doesn't change - it's just a reference to a specific commit.
Annotated tags, on the other hand, are complete objects that are stored in the Git database. They are verifiable and contain the tagger's name, email address, date and time, plus a tag message, and can be signed and verified using GNU Privacy Guard (GPG). It is often recommended to create a tag with a note so that you have all the above information.
However, if you just want a temporary tag, or for some reason don't want to keep this information, then you can also use a light tag.
Creating tagsโ
// Create a lightweight tag
git tag <tagname>
// Create a tag with notes
git tag -a <tagname>
You can also tag past commits. Simply enter the SHA-1 number of the commit.
// Tagging later
git tag <tagname> <commit-id>
View tagsโ
// List existing tags
git tag
// Show tag information
git show <tagname>
Sharing tagsโ
By default, the git push command does not transfer tags to the remote repository server. You must explicitly push tags to the shared server after they have been created.
// Push tags to the remote repository
git push origin <tagname>
// Push all tags
git push origin --tags
Delete tagsโ
// Delete tags
git tag -d <tagname>
// Delete the remote repository tag
git push origin --delete <tagname>
Git Aliasesโ
Git doesn't automatically infer the command you want when you type part of it. If you don't want to type in the full Git command every time, you can easily configure each command with the git config file to easily set an alias for each command. This looks like this.
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
We can then use git co as an equivalent instead of git checkout, and the same for the others.