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

eBook
€8.99 €17.99
Paperback
€22.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
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
Estimated delivery fee Deliver to Luxembourg

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

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 Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Luxembourg

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

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
€18.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
€189.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 €5 each
Feature tick icon Exclusive print discounts
€264.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 €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 80.97
Git Version Control Cookbook
€36.99
Git Best Practices Guide
€22.99
Git Essentials
€20.99
Total 80.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 the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela