Git is a powerful tool that can help to manage code. But sometimes we don’t know or we are scared about the features aren’t know. At least is our code and don’t want to lose any line of them.
Following the previous git post: Basic Git commands, we talk about branches.
The branch is a powerful feature of git. If like we copy all code to a new directory and begin work there. But the main difference is that git knows how to join or merge these two directories without broke or lose any line of code and all in the same directory ;)
Then, we want to show how to manage branches and easiest that is.
First of all, we need to make a dir and init a new repository:
1 2 3 4 | $ mkdir ebavs-git-test $ cd ebavs-git-test $ git init Initialized empty Git repository in /var/sites/ebavs-git-test/.git/ |
Now it’s time to create some code:
1 2 3 4 5 6 7 8 | $ echo "<?php echo 'hello';" > hello.php $ cat hello.php <?php echo 'hello'; $ git add . #adding files to repo $ git commit -a -m "say hello" [master (root-commit) 117a36c] say hello 1 file changed, 1 insertion(+) create mode 100644 hello.php |
It’s time to see branches and create new ones:
1 2 3 4 5 6 7 | $ git branch * master $ git checkout -b second #create branch named second Switched to a new branch 'second' $ git branch # list branch master * second |
Now we have two branches. Made some changes to hello.php, and test what happened:
1 2 3 4 5 6 7 | $ echo "echo 'say good bye';" >> hello.php #adding code $ cat hello.php <?php echo 'hello'; echo 'say good bye'; $ git commit -a -m "say bye" # commit changes [second be2743e] say bye 1 file changed, 1 insertion(+) |
Time to see differences:
1 2 3 4 5 6 7 8 9 10 | $ git branch # list branch master * second $ cat hello.php # content of hello.php <?php echo 'hello'; echo 'say good bye'; $ git checkout master # change branch Switched to branch 'master' $ cat hello.php # content of hello.php <?php echo 'hello'; |
We are in master and time to merge branches, now we say: merge second into master:
1 2 3 4 5 6 7 8 | $ git merge second # merge two branch Updating 117a36c..be2743e Fast-forward hello.php | 1 + 1 file changed, 1 insertion(+) $ cat hello.php # see what happenned <?php echo 'hello'; echo 'say good bye'; |
Merge two branches we don’t need the second branch, time to remove:
1 2 3 4 | $ git branch -d second #remove branch Deleted branch second (was be2743e). $ git branch * master |
This kind of work with git gives us the opportunity to work in different code branch with different features, it’s like work in different directories without worry about mix code later.