git config --global user.name "Your Name"
git config --global user.email "your_email@whatever.com"
Для Unix
git config --global core.autocrlf input
git config --global core.safecrlf true
Для Windows
git config --global core.autocrlf true
git config --global core.safecrlf true
Настройки алиасов
[alias]
co = checkout
ci = commit
st = status
br = branch
hist = log --pretty=format:\"%h %ad | %s%d [%an]\" --graph --date=short
type = cat-file -t
dump = cat-file -p
Проверка настроек
git config --list
git config <key
Файл .gitattributes
# all files
* text=auto
# binary files
*.jpg binary
Файл .gitignore
node_modules/
git init
git clone <url> <catalog>
git status
git status -s (status --short)
# непроиндексированные изменения
git diff
# проиндексированные
git diff --cached (--staged и --cached)
git add .
git add <file>
git commit -m "<message>"
# перезапись сообщения посл. коммита
git commit --amend -m "comment"
git rm <file>
git rm -f <folder>
# осталяет файл в рабочей директории
git rm --cached <file>
# принудительное удаление
git rm -f <file>
git mv <oldname> <newname>
git log --pretty=oneline
git log --pretty=format:"%h %ad | %s%d [%an]" --graph --date=short
Команда удалит все незакоммиченные изменения
# -f – force, -d – directory
git clean -fd
git checkout . | <branch> <file> <hash>
# discard changes in working directory
git checkout -- <file>
git restore <file>
git reset HEAD <file> # to unstage
git rm --cached <file> # удалить из индекса, но оставить в рабочей директории
git restore --staged <file>
# Unstage and discard changes made to a file, same as "git checkout <file>"
git restore --staged --worktree <file>
# Revert a file to some previous commit, same as "git reset <commit> -- <file>"
git restore --source HEAD~1 <file>
git reset --hard <hash | tag>
# для всех файлов
git reset --hard HEAD
При получении ссылки на коммит (т.е. хэш, ветка или имя тега), команда reset:
- Перепишет текущую ветку, чтобы она указывала на нужный коммит
- Опционально сбросит буферную зону для соответствия с указанным коммитом
- Опционально сбросит рабочий каталог для соответствия с указанным коммитом
# отменить коммит, сохранив все изменения на диске
git reset --soft HEAD~1
git commit --amend
# коммит с новыми изменениями, отменяющими предыдущие
git revert HEAD
git revert HEAD <hash> --no-edit
Добавление локальной ветки, которая отслеживает удаленную ветку
git branch --track <local-branch-name> <remote-origin-name>/<local-branch-name>
Переключение веток без checkout
git switch other-branch
git switch - # Switch back to previous branch, similar to "cd -"
git switch remote-branch # Directly switch to remote branch and start tracking it
Слияние
# Отмена слияния
git merge --abort
# Игнорирование пробельных символов
git merge < -Xignore-all-space | -Xignore-space-change > whitespace
# Переброс коммита из одной ветки в другую
# Примечание: это не сработает, если вы уже сделали push в origin
# создайте новую ветку из текущего состояния master
git checkout -b имя-новой-ветки
# удаляем коммит из ветки master
git checkout master
git reset HEAD~ --hard
git checkout имя-новой-ветки
# ваш коммит теперь живет в новой ветке :)
# случайно закоммитили не в ту ветку!
# откатываем последний коммит, но не удаляем изменения
git reset HEAD~ --soft
git add . git stash
# переключаемся на нужную ветку
git checkout имя-верной-ветки
git stash pop
git add .
git commit -m "тут ваш комментарий"
# теперь изменения в нужной ветке
# список
git remote -v
# добавление
git remote add <origin-name> <origin-url>
# Получение изменений из удалённого репозитория
git fetch [remote-name]
# Отправка изменений в удаленный репозиторий
git push <origin-name> <branch-namr>
# Просмотр удаленного репозитория
git remote show origin
# переименование
git remote rename <old> <new>
# удаление
git remote rm paul
Как убрать из Git-репозитория файлы с конфиденциальной информацией
Не используйте команду pull, это составная команда и делает несколько действий сразу
git fetch --all
git rebase my_feature upstream/master
git fetch --all
git checkout -b my_feature upstream/master
git branch -D master