This How to use Git post will take you through the essentials needed to get started with Git.
First, before you can use Git, you need to install it on your system — so let’s start with the installation process.
How to install Git
You can easily install Git from the Git download webpage.
A handy way to check the version installed on your system is to run:
After the installation, it is necessary to keep it up to date whenever there is a new version.
How to update Git
If you are using a Windows system and your currently installed version is 2.16.1(2) or higher; freely get the latest version with this command:
Once you have the correct version installed on your system, you can then proceed with the setup process by initializing Git in your project’s directory.
How to initialize Git
Initialization is to make Git ready to start monitoring files in a specified directory.
To initialize Git in a directory currently not under version control, you need first to go inside that directory from your terminal.
Afterward, initialize Git in that project’s directory by running:
After running the command above, a Git repository, named
.git, will be created in the project’s folder.
- Initializing Git in a project does not mean Git is tracking anything in that project’s directory. The
git initcommand just creates the
.gitrepository where almost everything that Git stores and manipulates lives.
- If you are curious about the contents in the
.gitdirectory, check Plumbing and Porcelain for more info.
How to configure Git
After the installation and initialization process, it is essential to configure your username and email address — as Git permanently bakes these details into your commits. Thus, helping team members identify each commit’s creator.
To configure your identity, run the following commands — one by one — in your terminal:
git config --global user.name “Your Name” git config --global user.email “[email protected]”
--global option enables you to run the above commands only once. However, if you do not mind inputting your name and email for each project, you can omit the
How to change a project’s configuration
Suppose you need to change the configured name or email address for a specific project, go into that project’s directory and run the command(s) below — one after the other:
git config user.name “The New Name” git config user.email “[email protected]”
How to check your project’s configurations
You can see all your project’s configurations by running:
git config --list
Suppose you wish to confirm the value stored for a single configuration (for instance, your email). In such a case, use the
git config <key> command like so:
git config user.email
How to exit the Git configuration space
To exit the Git configuration space, press the Q key on your computer’s keyboard.
How to track your files with Git
Once you’ve initialized and configured Git in a specific working directory, you can begin to use Git to track changes in your choice file(s). But the file(s) to be monitored must be in the working directory in which you initialized Git.
To begin tracking file(s) in the initialized project’s folder, go into that project’s directory from the terminal and run:
git add <fileOrFolderName>
After running the command above, Git will add the specified file (or folder) to the staging area.
- Once Git adds a file (or folder) to its staging area, it means Git has started monitoring that file’s version for further modifications that may occur on it.
<fileOrFolderName>in the tracking command above with the file’s (or directory’s) pathname.
<fileOrFolderName>is the pathname of a directory. In that case, the
git addcommand will automatically add all the files in that directory into the staging area recursively.
How to stage quickly
You can attach additional options to the
git add command to help speed up the staging process — especially when there are multiple files to stage.
Below are options commonly used to quicken the process of adding multiple files to the staging area.
Option 1: “
-A flag to stage all modified and untracked files in a project’s entire working directory — regardless of the current project’s directory in which you are.
git add -A
-A flag used above is the shorthand notation for the
--all flag. You can use any one of the two flags to add all modified files to the staging area.
Option 2: “
-u flag to stage only modified files that you committed previously.
git add -u
-uflag will stage all modified files — currently being track — in the project’s entire working directory. This staging will occur regardless of the project’s folder you are in presently.
-uflag will not add any new file (that is, previously uncommitted files) to the staging area.
-uflag is the shorthand notation for the
--updateflag. You can use any one of the two flags to update all modified files currently under version control.
Option 3: “
.” (dot) Symbol
. (dot) flag to stage all modified and untracked files located only in the current project’s directory in which you are.
git add .
- A dot symbol means “current directory”. As such, the above command will stage all modified, and untracked files only of that project’s directory wherein the
git add .command got invoked.
- The dot is essential in the
- There must be a space between the
addcommand and the dot mark.
Option 4: “
*” (asterisk) Symbol
Technically, you can use the
git add * command also to stage multiple files. However, to prevent unexpected results, it is best to avoid using it.
Important information about staging in Git
Below are two key details you should always bear in mind whenever you stage files in Git.
Info 1: Staging does not save your files
Whenever you stage your files, it does not imply saving them into the Git directory.
Staging implies that you have added details about your staged file(s) into a file called “index” — located in the Git directory.
Info 2: Git commits staged files only
Only the file versions in the staging area get committed to subsequent historic snapshots — not the working directory’s versions.
How to commit files to Git
Whenever you commit your files to Git, it means you have stored the staged version of your working directory’s file(s) into the
To commit a file that is currently in the staging area, run:
git commit -m “Write a message about the file(s) you are committing”
Important information about committing files to Git
Below are six key details you should always bear in mind whenever you commit files to Git.
Info 1: The “-m” flag is optional
-m flag allows you to write your message in-line with the
commit command. If you omit it, your text editor will be launched with comments prompting you to enter your commit message.
In such a case, you can delete the editor’s comments and type in your commit message. Or you can leave the comments and add your commit message.
Once you’ve finished writing your commit message inside the text editor, exit it so that Git can create the commit.
Writing commit messages with a text editor provides the opportunity to write long notes — even with multiple paragraphs. However, for short commit messages, the in-line method is sufficient.
Info 2: Use the “-v” flag to see the changes you are about to commit
Suppose you prefer to use the text editor to input your commit message. In that case, you can, optionally, add the -v flag to the
git commit command like so:
git commit -v
By doing so, Git will include the diff of your changes into the editor so that you can see the exact changes you are about to commit.
In other words, use the
-v flag to include — at the bottom of the text editor’s commit message template — the differences between what you are currently committing and your previous commit.
The diff at the bottom of your text editor’s commit message template will not get included in your final commit message. Instead, it is only present to help you remember the changes you are about to commit — thereby making it easier to craft a good commit message.
Info 3: It pays to draft a good commit message
Crafting a good commit message will help your collaborators (and yourself — after some time) understand why you committed a specific version of your project’s file(s).
Additionally, it will help elucidate differences that exist between the file versions committed.
Info 4: Where does Git store committed files?
Committed files reside in the local Git repository — named
.git. You can find this directory inside the root of your project folders in which you’ve initialized Git.
Info 5: How to view your project’s commit history
You can view your project’s commit history by running:
The project’s directory — whose commit history you want to check — must be the current directory.
Info 6: How to commit without staging first
Suppose you wish to commit your changes without staging them first. In such a case, you can skip the staging area (that is, omit running the
git add command) by adding an
-a flag to your
git commit like so:
git commit -a
By so doing, Git will automatically stage all the files it is already tracking. After the automatic staging, it will then commit the files.
How to clone a Git repository
Git Cloning is mainly about getting (downloading) a copy of a
For instance, you may need a copy of a project you intend to modify. In such a case, getting a clone of the project’s
.git directory puts at your possession all the file versions the project’s contributor(s) have committed to the
To clone a repository, run:
git clone <theGitRepoURL> <state the place to put the cloned git folder>
By so doing, Git will download a copy of the specified
.git repository into the place you’ve identified.
<theGitRepoURL>with the URL of the
.gitdirectory you want to clone.
<state the place to put the cloned git folder>with your system’s location, wherein you want the cloned
.gitrepository to reside.
- Whenever you clone any remote repo, Git automatically names that repo’s URL “
origin”. However, you can specify a different name with the
git clone -o yourPreferredNamecommand.
How to tell Git to ignore specific files
Suppose you do not want Git to monitor specific files or folders — including not listing them as untracked. In such a case, you can create a
How to create a
To create a
.gitignore file, go into the root directory wherein the file(s) you want to ignore are. Then, run the command below on your terminal:
How to specify the files you want Git to ignore
After creating a
.gitignore file in your project’s root directory, open the
.gitignore file and write in it, the names of the file(s), folder(s), or filetype(s) you want Git to ignore.
You can use the hash symbol (
#) to include comments inside your
Example of a
An example of a
.gitignore file is:
# In a “.gitignore” file, an asterisk (*) is a wildcard symbol that # means zero or more characters — but not a slash (/) — can replace # the asterisk. # The command below will ignore any document starting with “abc” # located anywhere in this project: abc* # The command below will ignore all “.txt” filetypes located anywhere # in this project: *.txt # In a “.gitignore” file, an exclamation mark (!) means “important”. # The command below will track “readme.txt” filetypes, even though # you've instructed Git — through the asterisk command above — to # ignore all “.txt” files: !readme.txt # The command below will ignore any “package-lock.json” file located # anywhere in this project: package-lock.json # The command below will ignore only the “passwords.text” file # located in the specified directory: directory/of/passwords.text # This command below will only ignore the “NOTE” file in the current # directory — not in any other directory — of this project: /NOTE # The following command will ignore all the content inside any folder # named “modules”: modules/ # This command below will ignore all “.txt” files directly inside the # folder named “mix”: mix/*.txt # Note that the command above will still track all “.txt” files that # are in the subdirectories of the “mix” folder. For instance, it # will ignore “mix/test.txt” but will track “mix/real/test.txt”. # In a “.gitignore” file, double asterisks (**) mark — followed by a # slash (e.g., **/) — is a wildcard symbol that means zero or more # directories’ names can replace the double asterisks. # The command below will ignore all “.pdf” files inside both the # folder named “doc” and in any of its subdirectories: doc/**/*.pdf # The question mark (?) in the command below means any single # character — except a slash — can replace the question mark: sea?.txt # As such, the command above will ignore files like “seas.txt” or # “seat.txt”. However, it will not ignore files like “seats.txt”. # In a “.gitignore” file, a pair of square brackets “[...]” specifies # the range of characters acceptable for a single character position. # Below are some examples. # The command below means the character after character “n” can # either be character “s” or character “t”: plan[st].js # Therefore, the command above will match files like “plans.js” or # “plant.js”. But it will not match “plane.js” nor “plants”. # The command below means the character after character “n” can be # any character between numbers “3 to 9” inclusive: plan[3-9].js # Therefore, the command above will match files like “plan3.js” or # “plan5.js”. But it will not match “plan10.txt” nor “plan1”. # The following command means the character after character “n” can # be any character between letters “f to z” inclusive: plan[f-z].js # As such, the command above will match files like “plank.js” or # “plany.js”. But it will not match “plan2.txt” nor “plane”. # An exclamation mark within a square bracket “[!]” means “negate”. # The command below means the character after character “n” cannot be # character “s” nor character “t”: plan[!st].js # Therefore, the command above will match files like “plane.js” or # “plan2.js”. But it will not match “plans.js” nor “plant”.
.gitignore file serves to ensure files that are currently untracked remain untracked.
In other words, Git will not ignore any file it is already tracking — even if specified in a
.gitignore file — unless you delete such a file from the staging area.
Other Git commands you will find useful
Below are other Git commands you will find handy.
How to change your last commit message
git commit --amend
Suppose you wish to update the content of the file version you committed last. In such a case, make the changes to the version in your working directory. Then stage the modifications and run the command above.
In doing so, Git will automatically replace your last commit with this updated version.
--amend command cautiously — as amending a commit changes the commit’s SHA-1.
Therefore, to avoid confusing other collaborators, it’s best not to amend any commit you have pushed (shared).
How to check the status of your files
How to check where Git got installed on your system
How to compare the file version in the staging area with the most recent version committed into the Git directory
git diff --staged
The command above will show the difference between file version(s) in the staging area and the version(s) most recently committed to the Git directory.
How to compare the version of files in the working directory with the version you added to the staging area
git diffcommand shows the changes in a working directory’s files that you’ve not yet staged.
- By default,
git diffwill compare a working directory’s file version with the version in the staging area. However, for any file currently not in the staging area,
git diffwill compare the working directory’s version with the last committed version.
- Suppose nothing shows after running the
diffcommand above. In that case, it implies that there is the same version of files in the working directory and the staging area.
git diffcommand does not show the entire content of a file. Instead, it displays only the chunks.
- To make the chunk less cumbersome, add the
--color-wordsflag to the
git diffcommand (i.e.,
git diff --color-words). Thus, each chunk will include just the modified words — not lines — and their context.
How to confirm if a specific file or folder is in the
git ls-files | grep <fileOrFolderName>
<fileOrFolderName>in the command above with the name of the file (or directory) you want to check.
- If nothing shows after running the command above, it means the specified file (or folder) is not in the
grepcommand is a useful utility for searching for a specified pattern or characters and printing lines that match that pattern. For instance,
git ls-files | grep test.jswill look for and print lines that match
- Check Git’s grep documentation for additional options for the
How to delete a file from the working directory and the
git rm fileToDelete
- Suppose you only run
rm fileToDelete— that is, excluding the
gitcommand. In such a case, the specified file will only get deleted from the working directory. Therefore, Git will still track it as an unstaged change.
git rm fileToDeletewill delete the specified file from the working directory and automatically stage the removal.
As such, during the next commit, Git will delete the file from the
- Use the
-fflag to forcefully remove modified files (or files previously added to the staging area). For instance,
git rm -f fileToDelete.
- Use the
-rflag to remove a folder. For instance,
git rm -r fileToDelete.
How to open gitignore’s manual page
git help gitignore
The gitignore manual will open in your default browser.
How to remove a file only from the staging area and not from your working directory:
git rm --cached fileToDelete
How to rename a file
git mv currentFileName newFileName
How to replace a working directory’s file with its last committed version:
git checkout -- localFileToDeleteAndReplace
The command above is a dangerous command that will permanently delete all the changes in the local version of the specified file.
In other words, Git will replace the local version with the last committed version.
How to see all the files currently in the staging area and in the
How to see your project’s commit history
- After running the command above, if you get stuck on the Git console, just hit the Q key on your keyboard to exit.
- Suppose you wish to limit the number of commit histories displayed to the last three entries, add
git logcommand. For instance,
git log -3.
- A git log command will display only basic commit history details — such as the author, date, and commit message. However, if you also wish to include the diff introduced in each of the commits, add
--patch) to the
git logcommand. For instance,
git log -2 -p.
- You can make the
git log‘s output less cumbersome by adding the
--color-wordsflag — for instance,
git log -p -2 --color-words.
As a result of such addition, each chunk will include just the modified words — not lines — and their context.
- To display a summarized statistic of the changes that occurred in each commit, add the
--statflag to the
git logcommand. For instance,
git log --stat.
- See additional
git logoptions in Git’s “Viewing the Commit History” article.
How to skip writing a commit message
Suppose you made only minor modifications to your file, and you prefer not to write a commit message. In such a case, you can skip writing the commit text by adding the
--no-edit option to your
git commit command like so:
git commit --amend --no-edit
How to undo the staging of a specific file in the staging area
git reset HEAD fileToUnstage
How to undo the staging of all files in the staging area
How to write text into a file via the terminal
echo textToWrite >> fileToWriteInto
>>will append your text to the end of the file’s content.
>will overwrite any existing content of the specified file.
- Suppose you need to use symbols, like the exclamation mark (
!), prepend each with a backslash (
\) mark. In doing so, Git will analyze the character as a text — not a command.
Hello!!!into a file via the command line:
echo Hello\!\!\! >> fileToWriteInto
Dangerous Git commands
Commands that permit you to undo changes are generally dangerous because they can permanently delete your work — if you do it wrongly!
Therefore, be super careful with these commands!
Git’s Undoing Things article is a good read on tools for undoing changes.
How to share a Git repository
Sharing a Git repository online makes it easy for collaborators to collaborate on a project from anywhere, at any time.
Moreover, GitHub — a popular online platform used for sharing
.git repositories — takes Git collaboration to a whole new height.
To share your Git repository (i.e., your project’s committed file versions) on GitHub, follow our “How to host a Git repository on GitHub” guide.
Below are links to other valuable content on how to use Git.
Featured Image: Tools awl pliers by Deborah Breen Whiting
Get Helpful Resources in Your Inbox
A CodeSweetly Digest