Using git for Source Control 101
Using git for source control has become ubiquitous with software development, and has largely replaced older source control methods, including CVS, and Subversion (SVN). Here’s some of the more common git commands.
Initializing a Repository
Here are the basic commands to initialize from a new or existing repository. Note, that the git add , git commit , and git push commands are the most common commands that you will use, repeatedly, and in that order, when making changes to code that is under git source control.
# Git global setup git config --global user.name "Jeff" git config --global user.email "jeff@yourdomain.com" # Create a new repository git clone git@gitlabserver.yourdomain.com:GroupName/projectname.git cd projectname touch README.md git add README.md git commit -m "add README" git push -u origin master # Existing folder or Git repository cd existing_folder git init git remote add origin git@gitlabserver.yourdomain.com:GroupName/projectname.git git add . git commit git push -u origin master
Checking Status and Getting File Diffs
# show changes git status # show file diff of what has changed git diff -- myfolder/mfile.cpp
Reverting, Resetting, and Cleaning – Be careful with these next commands!
# revert changes made in working copy git checkout . git checkout HEAD # hard-reset of all un-pushed commits to master - WARNING: CARFUL WITH THESE ONE!!! git reset git reset --hard # run git clean -fd after these git reset --hard <commit_guid> # revert to a specific commit git revert <commit_guid_1> <commit_guid_2> # remove untracked files (new, or generated, e.g., .DS_store) git clean -f # add -n for a preview of what will be removed git clean -fdn # actually, remove untracked files and directories, not just a preview git clean -fd
Real-World Usage:
git reset --hard git clean -fd git checkout HEAD
Stashing, instead of Resetting
Instead of resetting, you can accomplish the same with git stash , and even use the changes later if you change your mind.
# basic stashing git stash git stash --all # removes all files and dirs from working copy # using it later, if you changed your mind git stash apply # or simply remove the stashed changes with git stash pop # removes latest stashed state w/out applying to working copy git stash drop