ESC
Comandi Git

Setup & Config

Command Description Example
git config --global user.name "Name" Set the name attached to all commits globally git config --global user.name "John Doe"
git config --global user.email "email" Set the email attached to all commits globally git config --global user.email "[email protected]"
git config --global core.editor "editor" Set the default text editor for commit messages git config --global core.editor "code --wait"
git config --global color.ui auto Enable helpful colorization of command line output git config --global color.ui auto
git config --list List all configuration settings and their values git config --list --show-origin
git config --global alias.<alias> <command> Create a shorthand alias for a git command git config --global alias.st status
git config --global --unset <key> Remove a specific global config setting git config --global --unset core.editor
git config --global init.defaultBranch main Set the default branch name for new repositories git config --global init.defaultBranch main

Basic Workflow

Command Description Example
git init Initialize a new empty git repository in current directory git init my-project
git clone <url> Clone a remote repository into a new directory git clone https://github.com/user/repo.git
git clone <url> <dir> Clone a repository into a specific directory name git clone https://github.com/user/repo.git my-dir
git status Show the state of the working directory and staging area git status -s (short format)
git add <file> Stage a specific file for the next commit git add index.html
git add . Stage all changes in the current directory git add .
git add -p Interactively stage chunks/hunks of changes git add -p (choose y/n for each hunk)
git commit -m "message" Commit staged changes with an inline commit message git commit -m "feat: add login page"
git commit -am "message" Stage all tracked changes and commit in one step git commit -am "fix: correct typo in header"
git commit --amend Modify the most recent commit (message or content) git commit --amend -m "Updated message"
git diff Show unstaged changes between working tree and index git diff src/app.js
git diff --staged Show staged changes that will go into the next commit git diff --staged
git rm <file> Remove a file from the working tree and staging area git rm obsolete.txt
git mv <old> <new> Move or rename a file, staging the change automatically git mv old-name.txt new-name.txt

Branching

Command Description Example
git branch List all local branches; current branch is marked with * git branch -a (list local and remote branches)
git branch <name> Create a new branch at the current commit git branch feature/login
git checkout <branch> Switch to an existing branch git checkout main
git checkout -b <branch> Create and switch to a new branch in one command git checkout -b feature/signup
git switch <branch> Switch to an existing branch (modern syntax) git switch develop
git switch -c <branch> Create and switch to a new branch (modern syntax) git switch -c feature/dashboard
git branch -d <branch> Delete a merged branch (safe delete) git branch -d feature/login
git branch -D <branch> Force delete a branch regardless of merge status git branch -D old-experiment
git branch -m <old> <new> Rename a branch git branch -m old-name new-name
git merge <branch> Merge a branch into the current branch git merge feature/login
git merge --no-ff <branch> Merge with a merge commit, preserving branch history git merge --no-ff feature/login
git merge --squash <branch> Squash all branch commits into one staged change git merge --squash feature/login
git rebase <branch> Reapply commits on top of another branch git rebase main
git rebase -i HEAD~n Interactively rebase last n commits (squash, reorder, edit) git rebase -i HEAD~3
git cherry-pick <commit> Apply changes from a specific commit onto current branch git cherry-pick a1b2c3d

Remote

Command Description Example
git remote -v List all remote connections with their URLs git remote -v
git remote add <name> <url> Add a new remote connection git remote add origin https://github.com/user/repo.git
git remote remove <name> Remove a remote connection git remote remove origin
git remote rename <old> <new> Rename a remote connection git remote rename origin upstream
git fetch <remote> Download changes from remote without merging git fetch origin
git fetch --all Fetch from all remotes git fetch --all --prune
git pull Fetch and merge changes from the tracking remote branch git pull origin main
git pull --rebase Fetch and rebase instead of merge git pull --rebase origin main
git push <remote> <branch> Push a branch to a remote repository git push origin main
git push -u <remote> <branch> Push and set upstream tracking for the branch git push -u origin feature/login
git push --force-with-lease Force push but fail if remote has unexpected changes (safer than --force) git push --force-with-lease origin feature/login
git push <remote> --delete <branch> Delete a remote branch git push origin --delete old-branch
git push --tags Push all local tags to the remote git push origin --tags

History & Log

Command Description Example
git log Show the commit history for the current branch git log --oneline --graph --decorate
git log --oneline Show compact one-line commit history git log --oneline -10 (last 10 commits)
git log --author="Name" Filter commit history by author name git log --author="John" --oneline
git log --since=<date> Show commits after a specified date git log --since="2024-01-01" --until="2024-12-31"
git log --grep="pattern" Search commit messages matching a pattern git log --grep="fix" --oneline
git log -p <file> Show changes introduced by each commit for a file git log -p src/app.js
git log --follow <file> Follow a file's history across renames git log --follow -p old-name.txt
git show <commit> Show details and diff of a specific commit git show a1b2c3d
git blame <file> Show who last modified each line of a file git blame -L 10,20 src/app.js
git shortlog -sn Show commit count per author, sorted by number git shortlog -sn --all
git diff <branch1>..<branch2> Show changes between two branches git diff main..feature/login
git bisect start Start a binary search for the commit that introduced a bug git bisect start; git bisect bad; git bisect good v1.0

Undo Changes

Command Description Example
git restore <file> Discard changes in working directory (unstaged) git restore index.html
git restore --staged <file> Unstage a file, keeping changes in working directory git restore --staged index.html
git reset HEAD~1 Undo last commit, keeping changes staged git reset HEAD~1 (soft reset by default)
git reset --soft HEAD~n Undo last n commits, keeping all changes staged git reset --soft HEAD~3
git reset --mixed HEAD~n Undo last n commits, unstaging changes (default) git reset HEAD~2
git reset --hard HEAD~n Undo last n commits and discard all changes permanently git reset --hard HEAD~1
git revert <commit> Create a new commit that undoes changes from a commit (safe for shared branches) git revert a1b2c3d
git revert HEAD Create a new commit that reverses the last commit git revert HEAD --no-edit
git stash Save uncommitted changes to a temporary stash git stash push -m "WIP: login feature"
git stash pop Apply the most recent stash and remove it from stash list git stash pop
git stash list List all stashed changesets git stash list
git stash apply stash@{n} Apply a specific stash without removing it git stash apply stash@{2}
git stash drop stash@{n} Remove a specific stash entry git stash drop stash@{0}
git clean -fd Remove untracked files and directories from working tree git clean -fd (use -n first to preview)

Advanced

Command Description Example
git tag <name> Create a lightweight tag at the current commit git tag v1.0.0
git tag -a <name> -m "msg" Create an annotated tag with a message git tag -a v1.0.0 -m "Release version 1.0.0"
git tag -d <name> Delete a local tag git tag -d v1.0.0
git submodule add <url> Add a git repository as a submodule git submodule add https://github.com/user/lib.git lib
git submodule update --init --recursive Initialize and update all submodules git submodule update --init --recursive
git reflog Show a log of all reference changes, useful for recovering lost commits git reflog show HEAD
git worktree add <path> <branch> Check out a branch into a new linked working tree git worktree add ../hotfix-tree hotfix/urgent
git archive --format=zip HEAD > out.zip Create a zip archive of the repository at HEAD git archive --format=tar HEAD | gzip > repo.tar.gz
git gc Run garbage collection to optimize repository performance git gc --aggressive --prune=now
git rev-parse HEAD Get the full SHA of the current HEAD commit git rev-parse --short HEAD (short SHA)

Domande Frequenti

Git è un sistema di controllo versione distribuito che tiene traccia delle modifiche nei tuoi file nel tempo. Permette a più sviluppatori di collaborare sullo stesso progetto senza sovrascrivere il lavoro altrui, mantiene una cronologia completa di ogni modifica effettuata, ti consente di sperimentare nei branch senza toccare il codice principale e rende semplice tornare a qualsiasi stato precedente. È lo standard del settore per la gestione del codice sorgente.

Ci sono diversi modi a seconda di cosa serve: "git revert HEAD" crea un nuovo commit che annulla l'ultimo — sicuro per i branch condivisi perché preserva la cronologia. "git reset --soft HEAD~1" annulla l'ultimo commit ma mantiene le modifiche nell'area di staging. "git reset --mixed HEAD~1" (il comportamento predefinito) annulla il commit e rimuove le modifiche dallo staging, lasciandole nella directory di lavoro. "git reset --hard HEAD~1" annulla il commit e scarta tutte le modifiche definitivamente — da usare con cautela. Evita i reset --hard su commit già inviati a un repository condiviso.

"git merge" combina due branch creando un nuovo commit di fusione con due commit padre. Questo preserva la cronologia completa di entrambi i branch ed è non distruttivo, ma può affollare il log di commit di fusione. "git rebase" sposta o ripete i tuoi commit su un altro branch, producendo una cronologia lineare e più pulita. Poiché rebase riscrive la cronologia dei commit, non fare mai rebase di commit già inviati a un branch remoto condiviso: causerebbe problemi agli altri contributori.

HEAD è un puntatore speciale che fa riferimento al commit attualmente estratto — in sostanza dice a Git "dove ti trovi adesso" nella cronologia del repository. Di norma, HEAD punta alla cima del branch corrente. Quando cambi branch con "git checkout", HEAD si sposta al nuovo branch. HEAD~1 indica il commit precedente a HEAD, HEAD~2 due passi indietro, e così via. Lo stato "HEAD staccato" si verifica quando HEAD punta direttamente a un hash di commit anziché a un nome di branch.

Quando si verifica un conflitto di merge, Git sospende la fusione e contrassegna i file in conflitto. Apri ogni file in conflitto — Git inserisce dei marcatori che mostrano "<<<<<<< HEAD" (le tue modifiche), "=======" (il divisore) e ">>>>>>> nome-branch" (le modifiche in arrivo). Modifica il file per conservare il codice corretto, rimuovendo completamente i marcatori di conflitto. Poi aggiungi il file risolto all'area di staging con "git add " e completa il merge con "git commit". Strumenti come VS Code, IntelliJ o "git mergetool" offrono un'interfaccia visiva per semplificare la risoluzione dei conflitti.