Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Git Best Practices Guide
Git Best Practices Guide

Git Best Practices Guide: Master the best practices of Git with the help of real-time scenarios to maximize team efficiency and workflow

Arrow left icon
Profile Icon PIDOUX Eric
Arrow right icon
Free Trial
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1 (1 Ratings)
Paperback Nov 2014 102 pages 1st Edition
eBook
₱579.99 ₱1224.99
Paperback
₱1530.99
Subscription
Free Trial
Arrow left icon
Profile Icon PIDOUX Eric
Arrow right icon
Free Trial
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1 (1 Ratings)
Paperback Nov 2014 102 pages 1st Edition
eBook
₱579.99 ₱1224.99
Paperback
₱1530.99
Subscription
Free Trial
eBook
₱579.99 ₱1224.99
Paperback
₱1530.99
Subscription
Free Trial

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Git Best Practices Guide

Chapter 1. Starting a Git Repository

This chapter covers the basics needed to understand the topics discussed in this book, and of course, to improve your skills in Git. Commands in this chapter are used every day by all Git users. Some of them will not be explained in detail; they will be explained in another chapter.

In this chapter, you will learn about:

  • Initializing a repository
  • Cloning an existing repository
  • Adding and committing files
  • Pushing commits on remote repositories

Configuring Git

Before you start working on Git, you have to configure your name and e-mail by using the following commands:

Erik@local:~$git config --global user.name "Erik"
Erik@local:~$git config --global user.email erik@domain.com

Initializing a new repository

If you want to create a repository in an existing project, just type the following command line:

Erik@local:~$ cd myProject
Erik@local:~/myProject$ git init .

Otherwise, you have to create an empty directory and type git init inside it, as shown:

Erik@local:~$ mkdir myProject
Erik@local:~$ cd myProject
Erik@local:~/myProject$ git init

This will create a folder named .git inside the current directory that contains the following files used by Git:

  • Config: This is used with the configuration for the local Git repository
  • HEAD: This lists a file that is the current head branch
  • Refs directory: This contains references to a commit for a branch

Cloning an existent repository

With Git, it is possible to clone an existent repository to work on it.

There are several possibilities to clone a repository, but the http, git, and ssh protocols are used the most.

If the repository is public, it will create a folder and everything inside the folder. However, if the repository is private or protected, you have to enter an access information or provide a private ssh key. For example, if you want to clone a Symfony2 repository, type this line to clone it using myProjectName as the folder name:

Erik@local:~/myProject$ git clone https://github.com/symfony/symfony.gitmyProjectName
Initialized empty Git repository in /var/www/myProjectName/.git/
remote: Counting objects: 7820, done.
remote: Compressing objects: 100% (2490/2490), done.
remote: Total 7820 (delta 4610), reused 7711 (delta 4528)
Receiving objects: 100% (7820/7820), 1.40 MiB | 479 KiB/s, done.
Resolving deltas: 100% (4610/4610), done.
Checking out files: 100% (565/565), done.

Tip

Note that the name after the clone command is optional. If there is no parameter after the repository location, the repository name will be used.

You probably read the line about compressing objects. In fact, before sending any content, Git compresses objects to speed the transmission.

We will see more uses of the clone command in the next chapter.

Working with the repository

We have to take a few minutes to look at the life cycle of a file inside Git.

A file will go through the following states, and the Git command line will take the file from one state to another. We will explain each state and its command line.

Working with the repository

The important part of this schema is the triangle between the three states UNMODIFIED, MODIFIED, and STAGED. This triangle is an infinite loop. Indeed, every time you change a file, its state is set to modified, and then staged; when you commit the file, it returns to the unmodified state, and so on.

UNTRACKED is the first state where the file is created, but this isn't tracked by Git.

To change the state of a file, you have to add it.

Adding a file

When you start an empty repository and add a file, it will be in the untracked state, which means that it isn't in the Git repository.

To track a file, you have to execute this command line:

Erik@local:~/myProject$ touch MyFileName.txt
Erik@local:~/myProject$ echo "test" > MyFileName.txt
Erik@local:~/myProject$ git add MyFileName.txt

So, your file is now tracked by Git.

If you want to add all files because you already have something inside the directory while you create the repository, add a period (.) just after git add to specify to take all files inside the current directory:

Erik@local:~/myProject$ echo "hello" > MyFile2.txt
Erik@local:~/myProject$ echo "hello" > MyFile3.txt
Erik@local:~/myProject$ git add .

The file is currently staged and ready to be committed inside the repository.

Committing a file

As soon as your file is tracked, all changes will be notified by Git, and you have to commit the change on the repository.

Tip

Remember to commit your change as soon as possible (not for every line, but it's a marker to validate what you have done).

The commit command is local to your own repository, nobody except you can see it.

The commit command line offers various options. For example, you can commit a file, as shown in the following example:

Erik@local:~/myProject$ git commit -m 'This message explains the changes' MyFileName.txt

To commit everything, use the following command:

Erik@local:~/myProject$ git commit -m 'My commit message'

You will create a new commit object in the Git repository. This commit is referenced by an SHA-1 checksum and includes various data (content files, content directories, the commit history, the committer, and so on). You can show this information by executing the following command line:

Erik@local:~/myProject$ git log

It will display something similar to the following:

Commit f658e5f22afe12ce75cde1h671b58d6703ab83f5
Author: Eric Pidoux <contact@eric-pidoux.com>
Date: Mon Jun 2 22:54:04 2014 +0100
My commit message

The file is in the unmodified state because you just committed the change; you can push the files in the remote repository.

Pushing a file

Once committed, you can push the files in the remote repository. It can be on a bare repository, using init with the git init --bare command, so just type the following command:

Erik@local:~/myProject$ git push /home/erik/remote-repository.git

If you create a remote repository on another server, you have to configure your local Git repository.

If you use Git 2.0 or later, the previous command will print out something like this on the screen:

Warning: push.default is unset; its implicit value is changing in
Git 2.0 from 'matching' to 'simple'. To squelch this message
and maintain the current behavior after the default changes, use:
gitconfig --global push.default matching
To squelch this message and adopt the new behavior now, use:
gitconfig --global push.default simple

The 'matching' value from the push.default configuration variable denotes that git push will push all your local branches to the branches with the same name on the remote. This makes it easy to accidentally push a branch you didn't intend to.

The 'simple' value from the push.default configuration variable denotes that git push will push only the current branch to the branch that git pull will pull from; it also checks that their names match. This is a more intuitive behavior, which is why the default should be changed to this configuration value.

Firstly, check if a remote repository is defined:

Erik@local:~/myProject$ git remote

If it's not, define the remote repository named origin:

Erik@local:~/myProject$ git remote add origin http://github.com/myRepoAddress.git

Now, push the changes using the following command:

Erik@local:~/myProject$ git push -u origin master

After this, you will have a resume of what was pushed.

In fact, the remote repository will check the current Head (the reference to the commit) and compare it with its own. If there are differences between them, it will fail.

Removing a file

If you don't want a file anymore, there are two ways to remove it:

  • Delete the file manually and commit the changes. This will delete the file locally and on the repository. Use the following command line
    Erik@local:~/myProject$ git commit -m 'delete this file'
    
  • Delete the file only through Git:
    Erik@local:~/myProject$ git rm --cached MyFileName.txt
    

Checking the status

There is a way to display the working tree status, that is, the files that have changed and those that need to be pushed, and of course, there is a way to display the conflicts:

Erik@local:~/myProject$ git status

If everything is correct and up to date, you will get this result:

Erik@local:~/myProject$ git status
# On branch master
nothing to commit, working directory clean

If you add a file, Git will warn you to track it by using the git add command:

Erik@local:~/myProject$ touch text5.txt
Erik@local:~/myProject$ git status
# On branch master
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#   text5.txt
nothing added to commit but untracked files present (use "git add" to track)

If you edit MyFile2.txt and type git status again, then you will have new lines:

Erik@local:~/myProject$ echo "I am changing this file" > MyFile2.txt
Erik@local:~/myProject$ git status
# On branch master
# Changes to be committed:
#   (use "gitreset HEAD<file>..." to unstage)
#
#   new file: text5.txt
# 
# Changes not staged for commit:
#   (use "git add <file>…" to update what will be committed)
#
# modified: MyFile2.txt
#

On these lines, separate paragraphs display all files in each state. The MyFile2.txt file is not tracked by Git and text5.txt is ready to be committed.

If you add text5.txt using the git add command, you will notice the following changes:

Erik@local:~/myProject$ git add MyFile2.txt
Erik@local:~/myProject$ git status
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   new file:   text5.txt
#   modified:   MyFile2.txt
#

Ignoring files

Git can easily ignore some files or folders from your working tree. For example, consider a website on which you are working, and there is an upload folder that you might not push on the repository to avoid having test images in your repository.

To do so, create a .gitignore file inside the root of your working tree:

Erik@local:~/myProject$ touch .gitignore

Then, add this line in the file; it will untrack the upload folder and its contents:

upload

Files or folders you define in this file will not be tracked by Git anymore.

You can add some easy regex, such as the following:

  • If you want to ignore all PHP files, use the following regex:
    *.php
    
  • If you want to ignore all files having p or l at the end of its name, use the following regex:
    *.[pl]
    
  • If you want to ignore all temporary files (finishing by ~), use the following regex:
    *~
    

If the file is already pushed on the repository, the file is tracked by Git. To remove it, you will have to use the gitrmcommand line by typing this:

Erik@local:~/myProject$ git rm --cached MyFileName.txt

Summary

In this chapter, we saw the basics of Git: how to create a Git repository, how to put content in it, and how to push data to a remote repository.

In the next chapter, we will see how to use Git with a team and manage all interactions with a remote repository.

Left arrow icon Right arrow icon

Description

If you are a developer and you want to completely master Git without heavy theory, this is the book for you. A reasonable knowledge level and basic understanding of Git concepts will get you started with this book.

What you will learn

  • Create a Git repository and learn how to push your code to the repository Discover the easiest Git commands to use and manage your repository Learn how to find and resolve conflicts and mistakes Explore Git with your team members using commands such as clone, pull, and branch Set up Git for Continuous Integration to improve workflow Understand tag commits for mapping the application version An introduction to repository management and other Git tools

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 20, 2014
Length: 102 pages
Edition : 1st
Language : English
ISBN-13 : 9781783553730
Vendor :
GitHub
Category :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Nov 20, 2014
Length: 102 pages
Edition : 1st
Language : English
ISBN-13 : 9781783553730
Vendor :
GitHub
Category :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₱260 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₱260 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 5,409.97
Git Version Control Cookbook
₱2500.99
Git Best Practices Guide
₱1530.99
Git Essentials
₱1377.99
Total 5,409.97 Stars icon
Banner background image

Table of Contents

6 Chapters
1. Starting a Git Repository Chevron down icon Chevron up icon
2. Working in a Team Using Git Chevron down icon Chevron up icon
3. Finding and Resolving Conflicts Chevron down icon Chevron up icon
4. Going Deeper into Git Chevron down icon Chevron up icon
5. Using Git for Continuous Integration Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
(1 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 100%
R. Wenner Apr 13, 2015
Full star icon Empty star icon Empty star icon Empty star icon Empty star icon 1
First and most annoyingly, the title is misleading. This is not a Best Practices book, this is the bare minimum of commands, cobbled together for people who never used git before. Only the last chapter gets into actual practices, but it is nothing more than an commentated rehash of blog posts on that topic.The book shows commands but does not explain the "why" behind them. For example, it tells you that you can push changes, but does not mention what pushing means or when and why you would do it. It tells you that you can have tracked and untracked branches, but does not say anything on why or why not you would want to do that. It does not even tell anything on why you would want branches at all. From a book called "Best Practices" I would expect a discussion on how to set up my branches and when to merge them. The author explains how you run the rebase command, but not why. From a BestPractices book I expect the pros and cons of rebasing and when and when not to use it.The book is incomplete; it refers to private and public branches without explaining what these are.Some example commands don't work as given. And that is not only because of missing spaces or e.g. botched stash names (stash@"1} instead of stash@{1}). Did this book have a copy editor?Some explanations are imprecise or plain wrong. For example, contrary to what the author states, git status does not magically print which files "need to be pushed". (How could it know what makes sense to push?) While the author mentions pros and cons of different repository access protocols, he doesn't even mention "encryption" when talking about SSH. When the author briefly touches on semantic versioning, he only mentions bug fixes, and as a beginner you may wonder how features fit in here. A hook script uses a /bin/sh shebang line and the author claims it's a bash script. Have fun with that on a system where /bin/sh does not default to bash, like Debian.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.