DEV Community

joespaf
joespaf

Posted on

Basic Git Commands

Git repositories are files that track changes made to projects, allowing users to access alternative versions of their code. This has many useful applications, including collaborative coding, debugging, and drafting code before a final product. To be able to make use of these features, you must know what commands to call and in what order to do so.

Before you can make use of any git features, you need to give it a name for you as a user and an email to associate with your user.
Use the following commands to do so:
git config --global user.name "(insert name here)"
git config --global user.email "(insert email here)"

Now you can create a repository. Navigate to the directory containing your project and enter this command:
git init
This will create your repository, but it does not automatically fill it with the contents of the directory. To do so, you will need to stage them with the add command, which looks like this:
git add (file)
Or, if you want to add all files in the current directory:
git add --all

If you decide you don't actually want to add a file, or mistakenly added one you don't want tracked, you can use the restore command to remove it from staging. This command can also be used to restore a file to how it was in a previous commit.
git restore (file)
It can also be called with --staged in the place of (file) to remove all staged changes

Now these files are staged to be committed to the repository. You can see a list of all the files that the repository is tracking with the status command:
git status
This will also show the status of those files; whether or not they have changed since the last time they were committed.
That brings us to the commit command. This command will save the staged changes to the repository. Notably this does not overwrite any previous commits, so you can and should commit frequently. The command also takes a message to label the commit with, which should be used to describe the changes made since the last commit.
The commit command looks like:
git commit -m "(description)"

After there is at least one commit in the repository, you can use the log command to see a list of all commits, along with their messages, authors, and when they were committed.
git log

The log command also provides a hash associated to each commit, allowing you to navigate to older commits with the checkout command. You could use the entire hash, but only the first seven characters are necessary.
git checkout (hash)

Top comments (0)