Tanner Babcock

  1. Linux
  2. Git for Beginners

Git for Beginners

Official Git Reference Manual

Atlassian Git Tutorials

GitHub Tutorials

Learn Git Branching

Creating a Repository

This tutorial assumes that the default branch for your repository's host is master. I believe for GitHub it is still master, but GitLab uses main. Please do not type "master" if you're on the main branch, and vice versa. Doing so will give you an error.

How to create and initialize a bare repository (i.e. a directory) for a site like GitHub:

$ mkdir my-cool-thing $ cd my-cool-thing $ git init Initialized empty git repository $ touch myFile.js $ cat > README.md # My Cool Thing Hey everyone, this is *my* cool thing. $ git add myFile.js $ git add README.md $ git remote add origin git@github.com:you/example.git $ git commit -m "Initial commit" [master f73ed8] Test 2 files changed, 7 insertions(+), 0 deletions(-) create mode 100644 myFile.js create mode 100644 README.md $ git push origin master Enumerating objects: 4, done. Counting objects: 100% (4/4), done. Delta compression using up to 8 threads Compressing objects: 100% (2/2), done. Writing objects: 100% (3/3), 261 bytes | 261 KiB/s, done. Total 3 (delta 1), reused 0 (delta 0) To github.com:you/example.git

What this series of commands does is: It creates a new directory, with two files inside of it. myFile.js, and README.md. It initializes an empty repository. These files are added to the "staging area", which is a kind of "place" you put your modifications.

The GitHub repository URL is added as the remote "origin": the default global URL. This needs to be done before anything can be pushed. The typical commit message for the first commit is "Initial commit". What git push origin master means, is: You are pushing to the master branch of the origin global location.

Git Commands

These are some basic commands to help get you up and running with Git. Please read the official documentation, too.

Command What It Does
$ git clone [repository URL] Clone a repository from GitHub, GitLab, CodeBerg, BitBucket, or some other provider. The repository URL should begin with "https", and end with ".git" - for example: git clone https://gitlab.com/Babkock/Dotfiles.git. You can use SSH-style URLs if you have your SSH key registered with your Git Hosting Provider, and you have your SSH agent running. For example: git clone git@gitlab.com:Babkock/Dotfiles.git.
$ git init Initialize an empty Git repository in the current directory. This creates an invisible directory ".git", which is present in every repository.
$ git remote add origin [repository URL] This command is very important when creating a new project in version control. GitHub for example (remember Git is not necessarily the same as GitHub), will give you a URL that looks like this: https://github.com/You/your-repo.git.
$ git add [file or directory] Add a newly changed file or directory to the staging area. The staging area is a place where files are selected to be committed. Just because you change a file, does not mean your changes have been staged. Adding a directory, like git add ., will automatically add all of the changed files in that directory.
$ git rm [unwanted file] Removes the file from the repository, AND actually deletes it! The only way to restore a file deleted this way is with git checkout or git reset --hard
$ git rm -r [unwanted directory] Does the same for an entire directory. The "-r" option, for most essential Linux commands (cp, rm, chmod), can be assumed to make the command operate recursively: through a whole directory, and its sub-directories.
$ git rm --cached [retracted file] This is like safe mode git rm. This deletes the file from the repository (marks it for deletion in the staging area), but retains the actual file. This adds the "rm" change to your current staged changes.
$ git mv [existing file] [new filename] Move or rename an existing file, to a new directory, or new filename.
$ git status Your best friend. This command tells you all staged and unstaged changes for the repository, since the last commit. Staged changes are in green, unstaged changes are in red.
$ git log Show a list of recent commits, with their commit messages, authors, and hashes, for the repository.
$ git checkout [branch or commit] -- [specific file] This command allows you to browse the Git repository as it appeared in a specific commit in time. You can get a list of commit hashes (those 6-digit hexadecimal numbers) from the git log command. You can check out the whole repository, or simply look at an individual file. For example, if a repository has a branch called "dev", you would do git checkout dev. Or, if you've tracked that something important happened at commit d3ad69, you can also type git checkout d3ad69. To retrieve only a single file from that commit, use git checkout d3ad69 -- filename.txt.
$ git checkout -b [new branch name] Create a new branch and switch to it. This only creates the new branch in your local repo, not on the global repo.
$ git commit -m "commit message" This is the command that writes your staged changes in stone, for all future programmers. Committing saves all of your saved changes, and then waits to be pushed. You can commit several times before you push, and all of the commits will send at once. Make sure your commit message is always enclosed in "quotes". You can quickly add all unstaged changes and commit them with the "-a" option, such as git commit -a -m "commit".

When you commit for the first time, you will possibly be prompted to enter information about yourself: Your name and email address. This information is saved in ~/.gitconfig. Your name and email are pretty much what associate you with your commits, and your GitHub will automatically link your profile if you're committing with the same email address.

$ git reset --hard [remote/branch] This is the command that saves your ass if you ever fuck up a repository so much, that you just want to be abandon all of your changes and set it back to how it was. The command in this situation is usually git reset --hard origin/master.
$ git push [remote] [branch] Push (globally publish) the locally-saved commits to the global repository. This command is usually git push origin master, but can also be something like git push upstream dev. When and if you create a new branch for yourself and start committing to it (a very powerful development strategy anywhere), you will have to modify your "git push" command. Oh, and these names are optional. After pushing at least once, git push will assume the remote is "origin" and the branch is "master".
$ git pull [remote] [branch] Pull (retrieve the latest commits) and synchronize your local repository with the global one. This command always gives you a colorful summary of which files were changed, and how many additions and deletions there were. Unless you are using a branch name other than "master" or "main", this command will be either git pull origin master, or git pull origin main. This can be shortened to a simpler git pull.
$ git remote (set-url, get-url, add, remove) [remote] [repository URL] Add, remove, set a new URL for the given remote, or retrieve the existing remote URL. For example, if you've created a new repository on GitHub, and would like to connect your current directory to it, you would type git remote set-url origin https://github.com/You/project.git.
$ git diff [branch or commit] Show the differences (additions, deletions, and changes) between commits or branches. Remember, you can use git log to find the hashes of the commits, and you only need to type the first five or six digits. Running git diff with no arguments, however, will show all unstaged changes to the repository. To create a .diff file, simply redirect standard output from git to a file, like this: git diff > test.diff
$ git tag -a [version number] -m "Release message" Create a new tag (release) from the latest commit with arbitrary version number and release message. After you run this command, you must push your tag with the command git push origin [version number]. So if you made your version number "2.0", in your git tag command, you would then run git push origin 2.0.

Using SSH Keys

Official SSH-Keygen Tutorial

GitHub SSH Documentation

If you try to push to a private repository, GitHub or GitLab will prompt you for your password. It prompts you because you may be using an HTTPS URL, or your SSH key may not be registered, or your SSH agent may not be running. If you wish to push to public or private repositories without being prompted, you will have to create an SSH key, and then register it in the settings of your Git hosting provider.

This guide will show you how to create an SSH key.

To create an SSH key of the RSA type that is 4096 bits, run this command.

$ ssh-keygen -t rsa -b 4096

The shell will respond with something like this, and prompt you for a filename to save the key as.

Generating public/private rsa key pair. Enter file in which to save the key (/home/you/.ssh/id_rsa):

Here, you can save the key as any name you want. If you do not provide a full file path, Ssh-keygen will save the public and private keys in the current directory. All of your keys should reside in the .ssh directory in your home directory, so move them to ~/.ssh if they are not already there.

After you provide a name, the program will then prompt you for an optional passphrase. You do not have to use one, but if you do, it will provide an extra layer of security. To use no passphrase, just press Enter. This is like running a sudo command, the password will not be echoed on the screen as you type it.

Enter passphrase (empty for no passphrase): Enter same passphrase again:

If the two passphrases match, then the program will show you some output that looks like this.

Your identification has been saved in test Your public key has been saved in test.pub The key fingerprint is: SHA256:8A07BXsVDkP2oD2EvLD69WGtV92M2OA0yCRDfRDtcfY you@yourcomputer The key's randomart image is: +---[RSA 4096]----+ | oo+X+o. | | . =BoB+ o | | .o+*=+o+ . | | .o.*o.= E| | . S .+ = +.| | . ..o + + +| | . . o o . | | . o . | | . | +----[SHA256]-----+

If you had chosen the name "test", Ssh-keygen will have generated two files, test and test.pub. You may need to move these with the following command.

$ mv test{,.pub} ~/.ssh

In order to start committing quickly, you must give your newly-generated public key to GitHub or GitLab. Open the file ~/.ssh/test.pub in the text editor of your choosing (or, just cat it in the terminal and copy it from there). It will look like this.

ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDwcN+ZdmtdWfouT5YgNGzfwXp... you@yourcomputer

The part in the middle, of course, being a very long string of random characters. You must copy this entire string. For GitLab, you must click on your picture in the top-right, then select "Preferences" from the menu. There will be an option on the left called "SSH Keys". You will create a new SSH key and paste in the text from your test.pub file exactly.

For GitHub, click on your picture in the top-right, and then select "Settings" from the dropdown menu. The menu on the left will have an option called "SSH and GPG Keys", click on that. From here, you can paste in the text of your SSH key.

Congratulations, you have registered your newly generated SSH key with your Git hosting provider. Now, the only thing left to do is to start your Ssh-agent and add your new key to it. You can do that with two commands. Here is the first one.

$ eval $(ssh-agent) Agent 12345

This command creates a daemon of Ssh-agent that runs in the background. After running this, you must tell the agent about the new keys you've made.

$ ssh-add ~/.ssh/test Identity added: test (you@yourcomputer)

If you have moved your public and private key files (the private key has no extension) into your ~/.ssh directory, this command will run successfully. The part of the output that says you@yourcomputer is your username and hostname, much like what you would see in your shell prompt. Now you are free to commit to private repositories. You can also use the SSH URLs instead of the HTTPS URLs when cloning repositories. Committing should be much easier and quicker.

If you have a repo that has an HTTPS URL, and you want to change it to the SSH URL, you should check the URL first, like this.

$ git remote get-url origin https://gitlab.com/Babkock/Dotfiles.git

This will always prompt you for a password, since there is no SSH connection happening. If you want to change this to the SSH URL, you would type this.

$ git remote set-url origin git@gitlab.com:Babkock/Dotfiles.git

For example, if your GitHub username is JohnnyCool7, and your repository is "CoolPythonThing", the SSH URL of your repository would look like this:

git@github.com:JohnnyCool7/CoolPythonThing.git

So you would run a command like this, to change the remote's URL.

$ git remote set-url origin git@github.com:JohnnyCool7/CoolPythonThing.git

You will have to make sure your Ssh-agent is running, and the identity for your Git hosting provider has been added via Ssh-add, before you can start making commits, without being prompted for your password. You should put some kind of code in your shell's profile (.bashrc, .bash_profile, .zshrc, etc.) that automatically starts the agent. That code would look something like this.

eval $(ssh-agent) ssh-add "$HOME/.ssh/test"

Happy coding and committing! You are now a Git expert!

Signing Your Commits