GIT
GitHub Documentation
GitHub Skills
Git Visualization
Generate gitignore file online
Download: git_cheatsheet.pdf
Download: git_advanced.pdf
Command Quicklist
Command | Short Description |
---|---|
git init | Initialize repository |
git clone [repo_url] | Clone repository |
git status | View 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 branch | List 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 -v | View 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 log | View commit history |
git log --oneline | View short commit history |
git log --oneline --decorate --graph --all | View 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 diff | Diff of what is changed but not staged |
git diff --staged | diff of what is staged but not committed |
git tag | List tags |
git config --global user.name "name" | Set global username |
git config --global user.email "email" | Set global email |
git stash | Speichert uncommittete Änderungen im Stash und setzt das Arbeitsverzeichnis auf den letzten commit zurück |
git stash list | gestashte Änderungen anzeigen |
git stash apply | Anwendung des letzten Stashes |
git stash pop | Anwendung des letzten Stashes und löschung aus der Liste |
git stash apply stash@{n} | wendet den n-ten Stash der Liste an |
git stash clear | leert die Liste |
git stash branch neue-branch stash@{n} | Erstellt einen neuen Branch mit den gestashten Änderungen |
SSH: git@github.com:username/my-repository.git
HTTPS: https://github.com/username/my-repository.git
Grundlagen: Was ist Git?
Git ist ein verteiltes Versionskontrollsystem. Es verfolgt Änderungen im Code, ermöglicht parallele Entwicklung und das Zusammenführen von Arbeit.
Zentrale Begriffe:
- Repository (Repo): Projektverzeichnis, das von Git verwaltet wird.
- Commit: Ein Snapshot des Codes (inkl. Commit-Nachricht).
- Branch: Eine unabhängige Entwicklungslinie.
- Remote: Externes Repository (z.B. auf GitHub).
- Merge: Zusammenführen von Branches.
- Pull Request (PR): Anfrage zum Merge (GitHub UI).
The Staging Area
- Working Directory: The working directory is where you make edits and create new files. It represents the current state of your project.
- 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.
- 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.
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
Projekt starten
# Repository klonen
git clone https://github.com/benutzername/projekt.git
cd projekt
Feature-Branch starten
# Aktuelle Branches anzeigen
git branch -a
# Neuen Branch erstellen und wechseln
git checkout -b feature/kurze-beschreibung
Best Practice – Namenskonventionen:
feature/login-form
bugfix/falscher-pfad
hotfix/deployment-error
refactor/form-validation
Änderungen tracken & committen
# Status prüfen (Welche Dateien wurden geändert?)
git status
# Änderungen zur Staging-Area hinzufügen
git add DateiA.cs DateiB.cs
# oder alle Änderungen
git add .
# Commit mit Nachricht
git commit -m "Neue Login-Validierung implementiert"
Best Practices für Commits:
- Schreibe prägnante, beschreibende Nachrichten (im Imperativ).
- Feature, Bugfix, Refactoring, Hotfix, Doku
Branch pushen & PR erstellen
# Lokalen Branch auf Remote hochladen
git push -u origin feature/kurze-beschreibung
Danach GitHub öffnen und einen Pull Request gegen den Ziel-Branch erstellen, z.B.
develop
Remote-Änderungen holen
(z.B. develop
aktualisieren)
# Ziel-Branch holen und lokal updaten
git checkout develop
git pull origin develop
Feature-Branch aktuell halten
(optional, z.B. vor Merge)
git checkout feature/kurze-beschreibung
git merge develop
# Bei Konflikten: manuell lösen, dann
git add .
git commit
Branches löschen
# Lokal löschen
git branch -d feature/kurze-beschreibung
# Remote löschen
git push origin --delete feature/kurze-beschreibung
Weitere Nützliche Befehle
# Zeige Historie
git log --oneline --graph --all
# Dateien vergleichen
git diff # unstaged Änderungen
git diff --staged # staged Änderungen
# Änderungen rückgängig machen
git restore datei # unstaged Änderung verwerfen
git reset HEAD datei # aus staging entfernen
Advanced Operations
Commit & Branch Manipulation
- Letzten Commit behalten, aber z.b. nur die Änderungen hinzufügen.
git commit --amend --no-edit
- Checks out to the repository version of the file. (before Staging)
git checkout file-with-unwanted-changes.txt
- Macht den letzten Commit rückgängig, behält die Änderungen gestaged.
git reset --soft HEAD~1
- Macht den letzten Commit rückgängig, behält Änderungen unstaged.
git reset --mixed HEAD~1
- Letzten Commit rückgängig machen und Änderungen verwerfen.
git reset --hard HEAD~1
- Einzelnen Commit aus anderem Branch übernehmen.
git cherry-pick <commit>
- Creates and tracks the specified branch from origin on the remote repository.
git branch --track greet origin/greet
- Neuen Branch erstellen und direkt darauf wechseln.
git switch -c <neuer-branch>
- Wechselt zum vorherigen Branch zurück (super für schnelles Hin- und Herspringen).
git switch -
Historie & Diff
- Kompakter, visualisierter Verlauf aller Branches.
git log --oneline --graph --all
- Zeigt Änderungen (Patches) an einer bestimmten Datei im Verlauf.
git log -p <file>
- Zeigt Änderungen, die für den nächsten Commit vorgemerkt sind.
git diff --staged
- Unterschiede zwischen zwei Branches zeigen.
git diff <branchA>..<branchB>
- Zeigt, wer welche Zeile zuletzt geändert hat.
git blame <file>
Cleanup & Fehlerkorrektur
- Änderungen vorübergehend speichern (z.B. vor
git pull
).
git stash
- Gestashte Änderungen wieder anwenden.
git stash pop
- Nicht getrackte Dateien und Ordner entfernen (vorsichtig!).
git clean -fd
- Verlauf aller HEAD-Änderungen — nützlich zum Wiederherstellen verlorener Commits.
git reflog
- Prüft Repository auf verlorene Objekte (nützlich bei korrupten Repos).
git fsck --lost-found
Tagging
- Create a tag locally
git tag <tagname>
- Create annotated tag (recommended for releases)
git tag -a <tagname> -m "Your message here"
- Push tag to remote
git push origin <tagname>
- Delete Tag locally
git tag -d <tagname>
- Delete Tag on remote
git push origin --delete <tagname>
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:
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.
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 …
- If the branch is public and shared with others. Rewriting publicly shared branches will tend to screw up other members of the team.
- 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."