Skip to main content

GIT

GitHub Documentation
GitHub Skills
Git Visualization
Generate gitignore file online

Command Quicklist

CommandShort Description
git initInitialize repository
git clone [repo_url]Clone repository
git statusView repository status
git add [file]Stage changes of [file]
git add .Stage all changes
git reset [file]Unstage a file while retaining other changes
git rm [file]Delete file and stage the removal
git commit -m "message"Commit Changes
git branchList branches
git branch [branch]Create branch
git checkout [branch]Switch to branch
git checkout -b [new branchname]Create a branch and switch to it
git merge [branch]Merge branch
git remote -vView remotes
git remote set-url origin [NEW_GIT_URL_HERE]Set origin url for remote repo
git pull origin [branch]Pull changes
git push origin [branch]Push changes
git logView commit history
git log --onelineView short commit history
git log --oneline --decorate --graph --allView commit history with graphical layout (q to quit)
git revert [commit]Revert commit
git reset [commit]Reset to commit
git reset --hard [commit]Clear staging area, rewrite working tree from [commit]
git diffDiff of what is changed but not staged
git diff --stageddiff of what is staged but not committed
git tagList tags
git config --global user.name "name"Set global username
git config --global user.email "email"Set global email
git stashSpeichert uncommittete Änderungen im Stash und setzt das Arbeitsverzeichnis auf den letzten commit zurück
git stash listgestashte Änderungen anzeigen
git stash applyAnwendung des letzten Stashes
git stash popAnwendung des letzten Stashes und löschung aus der Liste
git stash apply stash@{n}wendet den n-ten Stash der Liste an
git stash clearleert die Liste
git stash branch neue-branch stash@{n}Erstellt einen neuen Branch mit den gestashten Änderungen
github repository URL's
SSH: git@github.com:username/my-repository.git
HTTPS: https://github.com/username/my-repository.git

The Staging Area

  1. Working Directory: The working directory is where you make edits and create new files. It represents the current state of your project.
  2. Staging Area: Once you've made changes in your working directory that you wish to save, you first add these changes to the staging area. This area captures a snapshot of the modifications and prepares them for committing.
  3. Repository: When you're ready to finalize your changes, you commit the modifications from the staging area. This action saves a permanent snapshot of the changes in your Git repository, along with metadata such as who made the changes and when.

Staging


git add <file>    # adds changes in a file to the staging area
git add . # adds all changes to the staging area
git diff # shows unstaged changes in the working directory
git dif --staged # shows changes that are staged for the next commit
git commit # commits the staged changes
git reset <file> # removes file from the staging area

UNSTAGE (Reverse) A FILE / ALL FILES

git restore --staged <file-path>   # unstage specified file
git restore --staged . # unstage all files

DISCARD LOCAL UNCOMMITTED CHANGES

git restore .            # discard all uncommitted changes
git restore path/to/file # discard changes to specified file
git checkout -- . # revert working directory to last commit

Common Operations

Undo local changes

(before Staging)

git checkout file-with-unwanted-changes.txt

Checks out to the repository version of the file.

Undo staged changes

(before commiting)

git reset HEAD staged-file-with-unwanted-changes.txt

Removes the file from the Staging Area. Changes in the file are still there (in the working directory), but now unstaged. To remove the changes checkout the file (see above).

Undo committed changes

git revert HEAD

Reverts the last commit (does not delete the last commit).

Removing commits

git reset --hard hashOfCommit

Use the hash or a tag to reset the head to. All commits up to this point will not be shown in the log. If a deleted commit has been tagged before it will show up when log is used with the --all argument. To delete it completely the tag has to be removed:

git tag -d tag-to-remove

Amend (add) to commit

git commit --amend -m "Add this commit to the last made commit"

Adds the new changes to the previous commit.

Move (and stage) Files

git mv source destination

Same as mv command, but the result is added to the staging area directly.

Add and track a branch

git branch --track greet origin/greet

Creates and tracks the specified branch from origin on the remote repository.

git pull vs git fetch

git fetch is used to download updates from a remote repository to your local repository without merging or modifying your local branches. This command allows you to review the changes before integrating them into your local branch.

git fetch <remote>

git pull is a combination of git fetch and git merge. It downloads changes and merges them into the current branch.

git pull <remote> <branch>

Change/Set remote URL

git remote -v                        # verify current remote repository
git remote set-url origin <new-url> # set new url of origin
git remote -v # verify new remote repository url
git fetch origin # sync local repository to new remote

Adding empty directories

Create a placeholder file named .gitkeep in the empty directory. The .gitkeep file has no special meaning to Git, but it’s a widely-accepted convention that signals the intention to keep the directory in the repository.

echo "" .gitkeep                                    # create .gitkeep file
git add .gitkeep # stage the file
git commit -m "add empty directory with .gitkeep" # commit the changes

Remove a directory

git rm -r <directory> # removes a dir from git repository recursively

Rebase, Reset, Merge

git reset --soft

When you use git reset --soft, Git moves the HEAD pointer to the specified commit while leaving the staging area and working directory unchanged. This means that all changes from commits after the specified one will remain in the staging area, ready to be recommitted.

git reset --soft HEAD~1

This command moves the HEAD pointer one commit back. Changes made in the latest commit are transferred to the staging area:

Soft-Reset

git reset --hard

The git reset --hard option can be thought of as a nuclear option. It moves the HEAD pointer to the specified commit, updates the staging area to match this commit, and also adjusts the working directory to exactly match the commit. Any changes from commits made after the specified commit will be completely discarded.

Alle lokalen Änderungen verwerfen und die Branch auf den Zustand des Remote-Repositories (z. B. origin/master oder origin/main) zurücksetzen:

git fetch origin
git reset --hard origin/master
git clean -fd # remove untracked files

git rebase

Rebasing effectively saves the changes in your current branch, temporarily “removes” the commits you’ve made on your branch, applies the new commits from the other branch, and then reapplies your changes one commit at a time on top of these.

It’s important to note that rebasing rewrites commit history by generating new commits for each original commit. This process can result in a cleaner and more understandable project history.

Git-Rebase

Above Situation:

git checkout feature  
git rebase main

After the rebase the Feature branch includes the commits from main and keeps the commits that have been commited earlier to the feature branch. The main branch is untouched, but the commitment history has changed.

If a conflict arises, Git will show you which files are conflicting. You’ll have to open these files, resolve the conflicts, and then continue the rebase like so:

# After resolving conflicts
git add .
git rebase --continue

If you want to abort the rebase for any reason, you can do so with the following command:

git rebase --abort

git merge

Once your feature is ready and tested, you’ll want to merge it back into the main project. First, switch back to the branch you want to merge your changes into. Assuming you want to merge your changes to main branch:

git checkout master

Then, merge your feature branch:

git merge <feature-branch>

After merging your changes locally, push them to the remote repository to make them available to your teammate and update the live version of the website:

git push origin master

When to Rebase, When to Merge?

Don’t use rebase …

  1. If the branch is public and shared with others. Rewriting publicly shared branches will tend to screw up other members of the team.
  2. When the exact history of the commit branch is important (since rebase rewrites the commit history).

Given the above guidelines, I tend to use rebase for short-lived, local branches and merge for branches in the public repository.

.gitignore FILE

Gecached Dateien aus gitignore entfernen:

git rm -r --cached .
git add .
git commit -m "Remove all files in .gitignore"

Check gitignore Syntax

git check-ignore -v <file>

Install & Config Script

git clone https://gist.github.com/a0947ac3153923fb4fb27385a76d56c0.git
# ===============================
# Script: git_setup.sh
# Beschreibung: Konfiguriert Git (Name, E-Mail), erzeugt SSH-Key und fügt ihn dem SSH-Agent hinzu.
# ===============================

# 1. Git global konfigurieren
read -p "Gib deinen Git-Benutzernamen ein: " GIT_USER
read -p "Gib deine Git-E-Mail ein: " GIT_EMAIL

git config --global user.name "$GIT_USER"
git config --global user.email "$GIT_EMAIL"

echo "Current Git config:"
git config --global --list

# 2. SSH-Key erzeugen
KEY_PATH="$HOME/.ssh/id_ed25519"
if [ -f "$KEY_PATH" ]; then
echo "SSH-Key bereits vorhanden unter $KEY_PATH"
else
ssh-keygen -t ed25519 -C "$GIT_EMAIL" -f "$KEY_PATH" -N ""
echo "SSH-Key wurde unter $KEY_PATH erzeugt."
fi

# 3. SSH-Agent starten und Key laden
eval "$(ssh-agent -s)"
ssh-add "$KEY_PATH"

# 4. Public Key anzeigen
echo "
-------- Kopiere diesen Public Key und füge ihn bei GitHub/GitLab hinzu: --------"
cat "$KEY_PATH.pub"
echo "----------------------------------------------------------------------------"

echo "Git-Setup abgeschlossen."