Git tutorial, getting started with Git

Below is a short comprehensive description of getting Git up and running in just a few minutes. I personally use OSX as a development machine and so the installation part of Git will cover an installation on OSX. If you like to install Git on another platform please take a look at the Git installation documentation. There are a lot of other ways to install Git, but the one described below seems to bring the least hassle on OSX.

Install Git and add your first project

  • First download the installer at the Google Git OSX installer project, http://code.google.com/p/git-osx-installer/downloads/list after running the installer you are good to go.
  • After this easy GUI installation it’s time to startup the terminal, although if you really are into GUI’s you can also download and install OpenInGitGui which can be found at http://code.google.com/p/git-osx-installer/wiki/OpenInGitGui. In your terminal go to the directory where your website is located and initialize a new repository here.

    $cd site_directory
    $git init

    You should now get a response like “Initialized empty Git repository in site_directory/.git/”. The next step is to add the current directory and all of its contents to the repository.

    $git add .
    $git commit -m "Initial import"

    You will now see that all files and directories are committed.

Basically this is it, nothing more to it. You could now start working with Git. Off course we can configure the Git installation just a little bit to set things right.

Basic configuration of Git, ignoring files and configuring the user settings
Whenever you will type “git status” on the current directory you will see if there are any changes that need to be committed, if so you can add them with the “commit” command like we did before. One of the first problems that you will bump into is that your cache files will also be committed. I personally don’t want to commit automatically created cache files or user content. So how can we deal with this? We can create a “.gitignore” file in the root of our project. You can find an example of the .gitignore file below.

*.cache
files

Now any file that has the *.cache extension will be ignored, also all the user content in the files directory will be ignored. This keeps our repository clean. By executing “git show” after committing the .gitignore file you will see that our ignore rules are correctly interpreted.

When you view the Git commit log of the project (“git log”) you will see that Git has already automatically used an author name and email address in the commits we did so far. These values are automatically detected by Git that examined your system configuration. You can change your name and email by executing the following commands:

$git config --global user.name Sjoerd Maessen
$git config --global user.email youremail@address.com

Taking advantage of Git
Off course we didn’t install Git just to add one project and change some basic settings. The power in any version control system is to make checkouts, revert and diff changes. Below you can find some basic commands that you will need to master.

$git checkout thepath
$git diff commitid1 commitid2
$git diff -- filepath
$git revert commitid1

The commands are pretty self explaining like all other commands of Git. If you already worked with other version control systems their is one thing to be aware of, “git revert” doesn’t behave like “svn revert” for example. “Git revert” will do a new commit to reverse a previous one, if you would like to undo your changes you should use “git checkout” instead. The things I have showed above are only small aspects of what Git is capable of. Cloning repo’s, tagging, branching, patching and resolving conflicts are all aspects that will make your life a lot easier, check them out at the Git community book

One more thing
There are some Git GUI repository browsers available that let you view who, why and when something was committed. One that is easy to setup and PHP only is viewgit, give it a try it will just run from your webserver!

http://viewgit.sourceforge.net

Comments

445 responses to “Git tutorial, getting started with Git”

  1. ShawnPhefs Avatar

    Эвакуатор в таганроге Услуги эвакуатора — это не только буксировка автомобиля: многие компании предлагают комплекс услуг, включающий эвакуацию после ДТП и проверку работоспособности систем автомобиля на месте, перевозку на ремонтную станцию, хранение на охраняемой стоянке, транспортировку мотоциклов и спецтехники, запуск двигателя или подзарядку аккумулятора, подвоз топлива по договоренности, оформление сопроводительной документации, помощь в страховых делах и аварийных ситуациях. Важно уточнять сроки, способ оплаты и наличие страховки на перевозку; при необходимости можно запросить сопровождение на русском языке, подтверждения выполнения работ и номер сменного водителя.

  2. ShawnPhefs Avatar

    Эвакуатор таганрог Эвакуатор — специализированная автотранспортная техника, предназначенная для перемещения автомобилей, которые не могут сами двигаться по дороге из-за поломки, ДТП или иных неисправностей. Обычно эвакуаторы оснащены тягловыми механизмами, лебедками, крюками, подъёмниками и креплениями, позволяющими надежно закрепить машину на платформе или на кузове. В зависимости от ситуации применяют эвакуаторы низкорамные или с кран-манипулятором; первые нужны для быстрого зацепления лёгких авто, вторые — для зацепа тяжёлых или нестандартных транспортных средств. Услуги эвакуатора могут включать буксировку на сервис или на штрафплощадку, доставку в автосервис, ремонт на месте, эвакуацию после ДТП, запуск двигателя, зарядку аккумулятора, подвоз топлива, а также оформление необходимых документов. Обращаться к лицензированным операторам рекомендуется через официальный сайт компании или по телефону диспетчера; чаще всего выдается квитанция/акт об оказании услуг. Вызов эвакуатора позволяет быстро убрать автомобиль с дороги, обеспечить безопасность дорожного движения и снизить риск дополнительных повреждений.

  3. ThomasSat Avatar

    копирайтер вакансии удаленная работа Вакансии удаленная работа — общий обзор публикуемых вакансий в удалённом формате. В них могут встречаться роли в IT, образовании, маркетинге, поддержке клиентов и дизайне. При выборе вакансии обращайте внимание на часы работы, требования к оборудованию, уровень оплаты и возможность карьерного роста. Подготовьте подробное резюме, кейс-материалы и портфолио, которое демонстрирует релевантность вашего опыта. Не забывайте про тестовые задания и собеседования в онлайн-формате, а также про проверку репутации работодателя.

  4. ThomasSat Avatar

    удаленная работа вакансии Фриланс для начинающих — стартовый этап на рынке фриланса: выбирайте узкую нишу, собирайте портфолио, делайте первые простые проекты и нарабатывайте отзывы. Важно понять свою ценность, установить разумные ставки и научиться вести переговоры с клиентами. Препятствия на старте включают конкуренцию и отсутствие репутации, поэтому используйте пробные задания и подписывайтесь на платформы, которые поддерживают новичков. Постепенно расширяйте спектр навыков: копирайтинг, дизайн, веб-разработка, маркетинг и аналитика.

  5. Binance Avatar

    Thanks for sharing. I read many of your blog posts, cool, your blog is very good. https://accounts.binance.info/es-AR/register?ref=UT2YTZSU

  6. LhaneDrync Avatar
    LhaneDrync

    I loved as much as you will receive carried out right here. The sketch is tasteful, your authored material stylish. nonetheless, you command get got an nervousness over that you wish be delivering the following. unwell unquestionably come more formerly again as exactly the same nearly very often inside case you shield this increase.
    https://fafafa388.com/melbet-kom-zerkalo-2025-obzor/

  7. Scottnus Avatar

    где ко ланта Для семей с детьми Ко Ланта — настоящая находка: пологие пляжи, спокойное море и множество безопасных развлечений. Мы часто устраивали пикники на берегу и играли в песке до заката. Вечерами заходили в рынки за свежими фруктами и местными лакомствами, а дома ближе к воде дарили потрясающие виды. Проживание в береговой зоне удобно — песок прямо у порога и море в шаговой доступности.

  8. DarrylVah Avatar

    шкаф купе на заказ москва Встроенная мебель для гостиной: Стильное и функциональное решение для вашей гостиной – встроенная мебель, изготовленная по вашим размерам и в соответствии с вашим дизайном.

  9. DarrylVah Avatar

    изготовление мебели на заказ в москве Встраиваемая прихожая на заказ: Оптимизируйте пространство прихожей с помощью встраиваемой мебели, изготовленной по вашим размерам и с учетом ваших потребностей.

  10. WilliamNAT Avatar

    ко ланта как добраться Пхукет – Ко Ланта: путешествие между двумя жемчужинами Таиланда. Лучшие маршруты и советы.

  11. StevenNet Avatar

    GSU Крупный учебный и научно-исследовательский центр Республики Беларусь. Высшее образование в сфере гуманитарных и естественных наук на 12 факультетах по 35 специальностям первой ступени образования и 22 специальностям второй, 69 специализациям.

  12. IsmaelNek Avatar
    IsmaelNek

    Hey there! Do you know if they make any plugins to help with Search Engine Optimization? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good success. If you know of any please share. Thanks!
    forticlient mac download

  13. StevenNet Avatar

    universities ГГУ имени Ф.Скорины

  14. StevenNet Avatar

    science, Francisk Skorina Gomel State University

  15. StephenGlona Avatar
    StephenGlona

    Howdy! This post could not be written any better! Reading through this post reminds me of my good old room mate! He always kept talking about this. I will forward this post to him. Pretty sure he will have a good read. Thanks for sharing!
    fortinet vpn

  16. StephenGlona Avatar
    StephenGlona

    This is really interesting, You’re a very skilled blogger. I’ve joined your feed and look forward to seeking more of your fantastic post. Also, I’ve shared your website in my social networks!
    Qfinder Pro

Leave a Reply

Your email address will not be published. Required fields are marked *