Git Tutorial: Committing Files

, , …,

continued from git Tutorial.

With git, you almost always commit to the local repository. Then, you push to a remote repository, or pull from a remote repository.

When using git, you should always cd to your project dir first.

Commit to Local Repository

How to commit a change to local repository?

After you made changes to the file, then you can commit your changes to local repository. To commit, cd to the working dir, then do:

# commit one file
git add myFile.py
git commit myFile.py -m "summary of what you changed."

Any file you want to commit, you must first git add, even if the file already exists in the repository.

The add command basically means add it to the “index” file. The purpose of “index” is for next commit. This “index” file is also called “staging area”.

More examples of commit:

# commit several files
git add file1 file2
git commit . -m "fixed bug 123."
# commit all files in current dir (not including newly created files)
git add .
git commit . -m "changed all python headers"
# commiting all files in current dir, including new or deleted file/dir
git add -A .
git commit . -m "added feature 872"

The -A option will include any new files in your dir, or files you removed. Basically, it'll commit your working tree to the local repository.

How to add a new file or dir?

Use the command add, then commit.

git add myFile.py               # add a new file
git commit myFile.py -m "summary of what you changed."

How to delete a file or dir?

Use the rm command, then commit. The rm command is like add, in the sense that both changes the staging area.

git rm file name
git commit file name -m"summary of change."
git rm -r dir name
git commit dir name -m"summary of change."

git will delete the files/dir for you.

If you already deleted the files, you can still call git rm to update the staging area, then do a commit.

With git, you normally never use git rm command. You simply {delete, add, change} files on your working tree in your normal work flow. When all's good, simply git add -A . then git commit . -m"msg". Git will automatically take care of removed files, or files that changed name.

# commiting all files in current dir, including new or deleted file/dir
git add -A .
git commit . -m "summary of what you changed."

Push (Commit) to Remote Repository

How to commit a change to remote repository?

git push url

This will push your local repository to the remote git server.

Ususually, you use git remote add to associate a name to ther remote server address. Then, you can just push using a name. Like this:

# cd to your project dir
cd ~/git/xah_emacs_init/

# associate a name to a remote server, for the git project of current dir
git remote add github https://github.com/xahlee/xah_emacs_init.git

# push code to the server associated with the name “github”
git push github

back to git Tutorial.

blog comments powered by Disqus