This blog shows how to use Git in a brand new project. It covers creating a repository, staging and commiting changes, adding a remote repository, and pushing commits.
Create or clone a Git repository¶
To use Git for version control, we need to have a Git repository. We can get it by initiating Git in a local directory or cloning a remote Git repository. First, go to the directory that we want Git to track for us and use one of the following commands to create a Git repository.
git init # initiate git in a local directory
git clone URL_or_SSH_key_of_remote_directory # clone a remote git repository from GitHub
Change status¶
We can make changes, e.g. create new files, in the directory and use git status
to check the status of the repository.
git status
If there is any new file, it should show up in untracked files. This means that Git has noticed the new file but hasn't started to track its changes.
Add files to repository¶
We can tell Git to track changes made to the file by using git add
to stage the changes.
git add file_name
Instead of a single file name, we can also use *
to add all files to Git or .
to add all files in the current directory.
Commit chagnes¶
If we want Git to save the staged changes of the directory, we can use git commit
to commit the staged changes.
git commit
This will pop up an editor to let us leave some commit messages about what has been changed in this commit. The commit will be made after we close the editor. In this commit, Git saves the changes made to the directory since the last commit. Hence, we can go back to a previous state of the directory by reverting one or more commits. Moreover, we can choose to revert a commit that was made several commits ago while keeping changes in later commits.
Add remote repository¶
We can share the changes to others by pushing the commit to a server like GitHub. First, add the remote repository using git remote add
.
git remote add origin URL_or_SSH_key_of_remote_directory
Push to remote repository¶
Then, push the commit to the remote repository using git push
.
git push -u origin branch_name
Now the changes are published on GitHub and shared with everyone that has access to the repository.
Pull commits from remote repository¶
If we are collaborating with other people, it is better to always keep the local directory updated by pulling the latest commits from the remote repository before we make any changes. We can do it using git pull
.
git pull
If everything looks good, we can make new changes to the directory and follow the add, commit, push workflow to save and share every progress.