Git windows горячие клавиши

One popular way for users to optimize their efficiency is to leverage shortcuts to interact with the UI. With Git tasks, like Committing, Pulling, and Pushing being part of your daily workflow, learning how to avoid leaving the keyboard for the mouse can keep you in the zone.

Git Shortcuts
Open Git Changes and shift focus to the Commit Message box Alt+G, C
Open the Git Repository Window Alt+G, M
Open the Branch Picker from the status bar Ctrl+Alt+F3
Open the Repository Picker from the status bar Ctrl+Alt+F4
Open the network operations context menu from the status bar Ctrl+E, Ctrl+C

Checkout some other shortcuts on this printable keyboard shortcut cheatsheet for Visual Studio available for download.

Try out the following Git keyboard workflows to see which shortcuts you can work into your daily practice. Not only can they help you be more productive and iterate quicker, but they can be easier to access for folks who don’t want to or are unable to move the mouse.

Create a New Branch with the Status Bar

Often, the first action of a new bug fix or some feature work is to create a new branch. To complete this action without using the mouse:

  • Use Ctrl+Alt+F3 to open the Branch Picker from the status bar.
  • Use Tab, then Enter to select the option for New Branch.
  • Type in the name of your new branch, then use the Tab key to cycle between the rest of the items (Shift+Tab cycles in the reverse direction, once the first item is in focus – meaning there’s a slim, dotted border around it, you can navigate using the Up and Down Arrow Keys).
    • For the dropdown menu tap Enter to open it, and navigate using the Up and Down Arrow Keys, using Enter to make your selection or Esc to exit the dropdown menu.
    • For the checkbox tap the Space to toggle it.
  • Use r or arrow/tab to Create and tap Enter to complete the action.

Commit Your Changes Faster

Once you update your code use Ctrl+S to save your work, then commit your changes without using the mouse:

  • Use Alt+G, C to focus the commit message text box in the Git Changes Window via the Top Level Menu.
  • Type your commit message, tapping Ctrl+Enter to commit all staged files or all changes if nothing is staged.
    • If you’d like to review your changes before committing, see the alternative flow below
  • Shift+Tab to back cycle to the Push icon and tap Enter to Push your changes.

Alternate Flow – Use the Diff View to quickly preview your changes

  • Tab to the document group you’d like review, use the arrow keys to focus the document, and tap Enter to open it in the Diff View.
  • Use Ctrl+F8 to view the next difference and Ctrl+Shift+F8 to view the previous difference.
  • Learn how to set your own keyboard shortcuts in the One Step Further with Customization section below, to perform actions like staging your files.

Quickly Navigate to View your Repo Status

Whenever you want to checkout manage your branches, use shortcut Alt+G, M to navigate quickly to the Git Repository Window. Again, using Tab and the Up and Down Arrows. Additionally, Alt+UP/DOWN arrows will allow you to navigate between sections, including the:

  • Branches (the left side selector)
  • History (the right side list)
  • Commit Details (actions for the commit, commit message)
  • Commit Diff

Learn more at Browse repos, compare branches & commits on Microsoft Learn.

Switch Active Repositories

Image Repo Picker Shortcut

Back in the status bar, you can also use the shortcut Ctrl+Alt+F4 to open the Repository Picker which allows you to quickly switch active repositories, bringing up the Git Repository Window for review.

One Step Further with Customization

Take the next step towards keyboard mastery by assigning your own Keyboard menu of the Options dialog. Get there by typing “Keyboard” into the search bar. For example, you can stage files using the keyboard, by assigning shortcuts to these commands:

  • Git.Remove – Works as a toggle. If a staged file is focused, it will be unstaged. If an unstaged file is focused, it will be staged. The name is not super friendly, so we introduced the next two.
  • Git.Stage – Stages an unstaged file. Doesn’t work in reverse.
  • Git.Unstage – Unstages a staged file. Doesn’t work in reverse.

To see all of the commands for git, type “Git” into the “Show commands containing:” search.

To learn more about how to customize key bindings checkout Identify and customize keyboard shortcuts.

Beyond Git Shortcuts

There’s a lot of content on Microsoft Learn to help you continue to make the most of the keyboard. You can start by checking out the most popular keyboard shortcuts for Visual Studio and dive deeper, including accessibility tips and tricks and learning how to use Visual Studio without a mouse. Find other productivity tips in the Productivity guide.

Thank You

Thanks for checking out ways to boost your productivity with Git keyboard shortcuts. Hopefully, these flows demonstrate how to make incorporating Git into your daily coding sessions easy and unobtrusive. If you have any feedback, use Developer Community to report an issue or Suggest a Feature for Visual Studio.

Author

Jessie is a Product Manager on the Visual Studio version control team, focusing on Git tooling and GitHub integration in the IDE.

ABOUT GIT-GUI

Git includes its local climate inside the terminal. All the new highlights are refreshed first at the order line, and just there is the full intensity of Git. Yet, plain content isn’t the easiest decision for all undertakings; here and there certain clients are substantially more OK with a point-and-snap interface, a visual portrayal is a thing that they need. 

Git GUI is a Tcl/Tk based graphical UI to Git. It centers around permitting clients to make changes to their storehouse by making new submits, altering existing ones, making branches, performing neighborhood blends, and bringing/pushing to far off archives. 

Most Used Git GUI keyboard shortcuts

Repo actions
Create branch Ctrl+B
Fetch all Ctrl+L
Stage the current file S
Stage all files Ctrl+Shift+S
Unstaged the current file U
Unstaged all files Ctrl+Shift+U
Commit staged files with the current message Ctrl+Enter
Stage all files and commit with the current message Ctrl+Shift+Enter
Focus commit message box Ctrl+Shift+M
Navigation
Select the next commit in the graph J or ↓
Select previous commit in the graph K or ↑
Select next item in a branch Shift+↓
Shift+J
Select previous item in a branch Shift+↑
Shift+K
Select first commit in the graph Ctrl+HOME
Select the last commit in the graph Ctrl+END
Undo Ctrl+Z
Redo Ctrl+Y
Ctrl+Shift+Z
Fuzzy Finder
Toggle Fuzzy Finder Ctrl+P
Search commits Ctrl+F
Open repo via Fuzzy Finder Ctrl+Shift+O
Search file to view history and blame Ctrl+Shift+H
Focus the left panel filter bar Ctrl+Alt+F
Open current repo in terminal Alt+T
Open current repo in File Manager Alt+O
Open diff or merge tool Ctrl+D
Close current repo Ctrl+W
Search within the file (if file content has focus) Ctrl+F
UI
Toggle Fullscreen Mode Ctrl+Shift+F
Increase Zoom Ctrl+»=»
Ctrl+»+»
Decrease Zoom Ctrl+»−»
Reset zoom Ctrl+0
Show or hide the left panel Ctrl+\
Focus the search bar Ctrl+F
Focus the left panel filter bar Ctrl+Alt+F
Close the current panel (if one is open) Esc
Tabs
New Tab Ctrl+T
Close Tab Ctrl+W
Swap to Tab #1-9 Ctrl + #1-9
Jump to the next open tab Ctrl+Tab
Jump to the previous open tab Ctrl+Shift+Tab

Сведения о сочетаниях клавиш

Если ввести ? в GitHub, откроется диалоговое окно со списком сочетаний клавиш, доступных для текущей страницы. С помощью этих сочетаний клавиш можно выполнять действия на сайте без использования мыши.

В параметрах специальных возможностей можно отключить сочетания символьных клавиш, сохранив сочетания клавиш-модификаторов. Дополнительные сведения см. в разделе Управление параметрами специальных возможностей.

С помощью GitHub Command Palette можно также получить быстрый доступ ко множеству действий без необходимости запоминать сочетания клавиш. Дополнительные сведения см. в разделе GitHub Command Palette.

В следующих разделах перечислены некоторые доступные сочетания клавиш, упорядоченные по страницам, на которых их можно использовать в GitHub.com.

Сочетания клавиш на уровне сайта

Сочетание клавиш Описание:
S или / Установка фокуса на панели поиска. Дополнительные сведения см. в разделе Сведения о поиске в GitHub.
G N Переход к уведомлениям. Дополнительные сведения см. в разделе Сведения об уведомлениях.
ESC Когда фокус находится на всплывающем окне с информацией о пользователе, проблеме или запросе на вытягивание, это всплывающее окно закрывается и фокус снова устанавливается на элементе, к которому оно относится.
COMMAND+K (Mac) или
CTRL+K (Windows и Linux)
Открывается GitHub Command Palette. При редактировании текста Markdown открыть палитру команд можно с помощью сочетания клавиш COMMAND+OPTION+K или CTRL+ALT+K. Дополнительные сведения см. в разделе GitHub Command Palette.

Репозитории

Сочетание клавиш Описание:
G C Переход на вкладку Код.
G I Переход на вкладку Проблемы. Дополнительные сведения см. в разделе Сведения о проблемах.
G P Переход на вкладку Запросы на вытягивание. Дополнительные сведения см. в разделе Сведения о запросах на вытягивание.
G A Переход на вкладку Действия. Дополнительные сведения см. в разделе Сведения о действиях.
G B Переход на вкладку Проекты. Дополнительные сведения см. в разделе Сведения о досках проектов.
G W Переход на вкладку Вики. Дополнительные сведения см. в разделе Сведения о вики-сайтах.
G G Переход на вкладку Обсуждения. Дополнительные сведения см. в разделе Сведения об обсуждениях.

Редактирование исходного кода

| Сочетание клавиш | Описание |————|———— |. | Открывает репозиторий или запрос на вытягивание в веб-редакторе на той же вкладке браузера. Для использования редактора необходимо войти в систему. Дополнительные сведения см. в разделе Веб-редактор.
|> | Открывает репозиторий или запрос на вытягивание в веб-редакторе на новой вкладке браузера. Для использования редактора необходимо войти в систему. Дополнительные сведения см. в разделе Веб-редактор. |COMMAND+B (Mac) или
CTRL+B (Windows и Linux) | Вставка форматирования Markdown для выделения текста полужирным шрифтом |COMMAND+I (Mac) или
CTRL+I (Windows и Linux) | Вставка форматирования Markdown для выделения текста курсивом |COMMAND+K (Mac) или
CTRL+K (Windows и Linux) | Вставка форматирования Markdown для создания ссылки |COMMAND+SHIFT+7 (Mac) или
CTRL+SHIFT+7 (Windows и Linux) | Вставка форматирования Markdown для создания упорядоченного списка |COMMAND+SHIFT+8 (Mac) или
CTRL+SHIFT+8 (Windows и Linux) | Вставка форматирования Markdown для создания неупорядоченного списка |COMMAND+SHIFT+. (Mac) или
CTRL+SHIFT+. (Windows и Linux) | Вставка форматирования Markdown для создания цитаты | E | Открытие файла исходного кода на вкладке Изменение файла |COMMAND+F (Mac) или
CTRL+F (Windows и Linux) | Начало поиска в редакторе файлов |COMMAND+G (Mac) или
CTRL+G (Windows и Linux) | Найти далее |COMMAND+SHIFT+G (Mac) или
CTRL+SHIFT+G (Windows и Linux) | Найти ранее |COMMAND+OPTION+F (Mac) или
CTRL+SHIFT+F (Windows и Linux) | Заменить |COMMAND+SHIFT+OPTION+F (Mac) или
CTRL+SHIFT+R (Windows и Linux) | Заменить все |ALT+G | Перейти к строке |COMMAND+Z (Mac) или
CTRL+Z (Windows и Linux) | Отмена |COMMAND+Y (Mac) или
CTRL+Y (Windows и Linux) | Повторить |COMMAND+SHIFT+P | Переключение между вкладками Изменение файла и Предварительный просмотр изменений |COMMAND+S (Mac) или
CTRL+S (Windows и Linux) | Запись сообщения о фиксации

Дополнительные сочетания клавиш см. в документации по CodeMirror.

Просмотр исходного кода

Сочетание клавиш Описание:
T Активация средства поиска файлов
L Переход к строке кода
W Переключение на новую ветвь или тег
да Развертывание URL-адреса в каноническую форму. Дополнительные сведения см. в разделе Получение постоянных ссылок на файлы.
I Отображение или скрытие комментариев к изменениям. Дополнительные сведения см. в разделе Комментарий к изменению запроса на вытягивание.
А Отображение или скрытие заметок к изменениям
B Открытие представления blame. Дополнительные сведения см. в разделе Трассировка изменений в файле.
Сочетание клавиш Описание:
COMMAND+B (Mac) или
CTRL+B (Windows и Linux)
Вставка форматирования Markdown для выделения текста полужирным шрифтом
COMMAND+I (Mac) или
CTRL+I (Windows и Linux)
Вставка форматирования Markdown для выделения текста курсивом
COMMAND+E (Mac) или
CTRL+E (Windows и Linux)
Вставляет форматирование Markdown для кода или команды в строке
COMMAND+K (Mac) или
CTRL+K (Windows и Linux)
Вставляет форматирование Markdown для создания ссылки
COMMAND+V (Mac) или
CTRL+V (Windows и Linux)
Создание ссылки Markdown при применении к выделенному тексту
COMMAND+SHIFT+P (Mac) или
CTRL+SHIFT+P (Windows и Linux)
Переключение между вкладками комментариев Запись и Предварительный просмотр
COMMAND+SHIFT+V (Mac) или
CTRL+SHIFT+V (Windows и Linux)
Вставляет html-ссылку в виде обычного текста
Команды+ Shift+ Параметр+ V (Mac) или
CTRL+SHIFT+ALT+V (Windows и Linux)
Вставка html-ссылки в виде обычного текста
COMMAND+SHIFT+7 (Mac) или
CTRL+SHIFT+7 (Windows и Linux)
Вставка форматирования Markdown для создания упорядоченного списка
COMMAND+SHIFT+8 (Mac) или
CTRL+SHIFT+8 (Windows и Linux)
Вставка форматирования Markdown для неупорядоченного списка
COMMAND+ВВОД (Mac) или
CTRL+ВВОД (Windows и Linux)
Отправка комментария
CTRL+ . затем CTRL+[номер сохраненного ответа] Открытие меню сохраненных ответов и автоматическое заполнение поля комментария сохраненным ответом. Дополнительные сведения см. в статье Сохраненные ответы Azure.
COMMAND+SHIFT+. (Mac) или
CTRL+SHIFT+. (Windows/Linux)
Вставляет форматирование Markdown для цитаты
COMMAND+G (Mac) или
CTRL+G (Windows и Linux)
Вставка предложения. Дополнительные сведения см. в разделе Просмотр предлагаемых изменений в запросе на вытягивание.
R Цитирование выделенного текста в ответе. Дополнительные сведения см. в разделе Базовый синтаксис записи и форматирования.

Списки проблем и запросов на вытягивание

Сочетание клавиш Описание:
C Создать проблему
COMMAND+/ (Mac) или
CTRL+/ (Windows и Linux)
Установка курсора на панель поиска проблем или запросов на вытягивание. Дополнительные сведения см. в статье Фильтрация и поиск проблем и запросов на вытягивание.
U Фильтрация по автору
L Фильтрация по меткам или их изменение. Дополнительные сведения см. в разделе Фильтрация проблем и запросов на вытягивание по меткам.
ALT и щелчок мышью Исключение меток при фильтрации по ним. Дополнительные сведения см. в разделе Фильтрация проблем и запросов на вытягивание по меткам.
M Фильтрация по вехам или их изменение. Дополнительные сведения см. в разделе Фильтрация проблем и запросов на вытягивание по вехам.
А Фильтрация по уполномоченным или их изменение. Дополнительные сведения см. в разделе Фильтрация проблем и запросов на вытягивание по уполномоченным.
O или ВВОД Открытие проблемы

Проблемы и запросы на вытягивание

Сочетание клавиш Описание:
Q Запрос рецензента. Дополнительные сведения см. в разделе Запрос проверки запроса на вытягивание.
M Задание вехи. Дополнительные сведения см. в разделе Связывание вех с проблемами и запросами на вытягивание.
L Применение метки. Дополнительные сведения см. в разделе Применение меток к проблемам и запросам на вытягивание.
А Задание уполномоченного. Дополнительные сведения см. в разделе Назначение проблем и запросов на вытягивание другим пользователям GitHub.
X Связывание с проблемой или запросом на вытягивание из того же репозитория. Дополнительные сведения см. в разделе Связывание запроса на вытягивание с проблемой.
COMMAND+SHIFT+P (Mac) или
CTRL+SHIFT+P (Windows и Linux)
Переключение между вкладками Запись и Предварительный просмотр
ALT и щелчок мышью При создании проблемы из списка задач откройте форму новой проблемы на текущей вкладке, удерживая клавишу ALT и щелкнув в правом верхнем углу задачи. Дополнительные сведения см. в разделе Сведения о списках задач.
SHIFT и щелчок мышью При создании проблемы из списка задач откройте форму новой проблемы на новой вкладке, удерживая нажатой клавишу SHIFT и щелкнув в правом верхнем углу задачи. Дополнительные сведения см. в разделе Сведения о списках задач.
COMMAND и щелчок мышью (Mac) или
CTRL+SHIFT и щелчок мышью (Windows и Linux)
При создании проблемы из списка задач откройте форму новой проблемы в новом окне, удерживая клавишу COMMAND или клавиши CTRL+SHIFT и щелкнув в правом верхнем углу задачи. Дополнительные сведения см. в разделе Сведения о списках задач.

Вкладка «Измененные файлы» в запросах на вытягивание

Сочетание клавиш Описание:
C Откройте раскрывающееся меню Фиксации , чтобы отфильтровать, какие фиксации отображаются в различиях.
T Перемещение курсора в поле «Фильтр измененных файлов»
Команды+ Shift+ Ввод (Mac) или CTRL+SHIFT+ВВОД (Windows/Linux) Отправка комментария к отзыву
Параметр и щелкните (Mac) или ALT и щелкните (Windows/Linux) Переключение между свертыванием и расширением всех устаревших или разрешенных комментариев проверки в запросе на вытягивание (например, удерживая нажатой клавишу ALT и нажав кнопку Показать устаревшие или Скрыть устаревшие).
Щелчок мышью, затем SHIFT и щелчок мышью Чтобы прокомментировать несколько строк запроса на вытягивание, щелкните номер строки, удерживайте нажатой клавишу SHIFT, а затем щелкните другой номер строки. Дополнительные сведения см. в разделе Комментарий к запросу на вытягивание.

Проекты

Навигация по проекту

Сочетание клавиш Описание:
Команды+ f (Mac) или CTRL+f (Windows/Linux) Поле фильтра фокусировки
Перемещение фокуса на ячейку влево
Перемещение фокуса на ячейку вправо
Перемещение фокуса на ячейку вверх
Перемещение фокуса на ячейку вниз

Управление проектом

Сочетание клавиш Описание:
ВВОД Переключение режима редактирования для ячейки с фокусом
ESCAPE Отмена редактирования для ячейки с фокусом
Команды+ Shift+\ (Mac) или CTRL+SHIFT+\ (Windows/Linux) Открытие меню действий со строками
SHIFT+ПРОБЕЛ Выбор элемента
ПРОБЕЛ Открытие выбранного элемента
e Архивация выбранных элементов

Projects (classic)

Перемещение столбца

Сочетание клавиш Описание:
ВВОД или ПРОБЕЛ Начало перемещения столбца с фокусом
ESC Отмена выполняемого перемещения
ВВОД Завершение выполняемого перемещения
или H Перемещение столбца влево
COMMAND+ или COMMAND+H (Mac) либо
CTRL+ или CTRL+H (Windows и Linux)
Перемещение столбца в крайнюю левую позицию
или L Перемещение столбца вправо
COMMAND+ или COMMAND+L (Mac) либо
CTRL+ или CTRL+L (Windows и Linux)
Перемещение столбца в крайнюю правую позицию

Перемещение карточки

Сочетание клавиш Описание:
ВВОД или ПРОБЕЛ Начало перемещения карточки с фокусом
ESC Отмена выполняемого перемещения
ВВОД Завершение выполняемого перемещения
или J Перемещение карточки вниз
COMMAND+ или COMMAND+J (Mac) либо
CTRL+ или CTRL+J (Windows и Linux)
Перемещение карточки вниз столбца
или K Перемещение карточки вверх
COMMAND+ или COMMAND+K (Mac) либо
CTRL+ или CTRL+K (Windows и Linux)
Перемещение карточки вверх столбца
или H Перемещение карточки вниз столбца слева
SHIFT+ или SHIFT+H Перемещение карточки вверх столбца слева
COMMAND+ или COMMAND+H (Mac) либо
CTRL+ или CTRL+H (Windows и Linux)
Перемещение карточки вниз крайнего левого столбца
COMMAND+SHIFT+ или COMMAND+SHIFT+H (Mac) либо
CTRL+SHIFT+ или CTRL+SHIFT+H (Windows и Linux)
Перемещение карточки вверх крайнего левого столбца
Перемещение карточки вниз крайнего правого столбца
SHIFT+ или SHIFT+L Перемещение карточки вверх крайнего правого столбца
COMMAND+ или COMMAND+L (Mac) либо
CTRL+ или CTRL+L (Windows и Linux)
Перемещение карточки вниз крайнего правого столбца
COMMAND+SHIFT+ или COMMAND+SHIFT+L (Mac) либо
CTRL+SHIFT+ или CTRL+SHIFT+L (Windows и Linux)
Перемещение карточки вниз крайнего правого столбца

Предварительный просмотр карточки

Сочетание клавиш Описание:
ESC Закрытие области предварительного просмотра карточки

GitHub Actions

Сочетание клавиш Описание:
COMMAND+ПРОБЕЛ (Mac) или
CTRL+ПРОБЕЛ (Windows и Linux)
Получение предложений для файла рабочего процесса в редакторе рабочих процессов.
G F Переход к файлу рабочего процесса
SHIFT+T или T Переключение меток времени в журналах
SHIFT+F или F Переключение журналов в полноэкранный режим
ESC Выход из полноэкранного режима журналов

Уведомления

Сочетание клавиш Описание:
E Пометить как выполненное
SHIFT+U Отметить как непрочитанное
SHIFT+I Пометить как прочитанное
SHIFT+M Unsubscribe (отмена подписки).

Сетевая диаграмма

Сочетание клавиш Описание:
или H Прокрутить влево
или L Прокрутить вправо
или K Прокрутка вверх
или J Прокрутка вниз
SHIFT+ (Mac) или
SHIFT+H (Windows и Linux)
Прокрутка до конца влево
SHIFT+ (Mac) или
SHIFT+L (Windows и Linux)
Прокрутка до конца вправо
SHIFT+ (Mac) или
SHIFT+K (Windows и Linux)
Прокрутка до конца вверх
SHIFT+ (Mac) или
SHIFT+J (Windows и Linux)
Прокрутка до конца вниз

Being a power user I cannot stress more on the fact that I need to be super-productive when it comes to programming and development. Completely eradicating my mouse is one of the best things I did as it boosted my productivity more than twice. I thought it would be a nice gesture to share the details with the world of developers.

Contents

  1. Basics
  2. Shortcuts
    1. Basic Status & Adding
    2. Adding & Committing
    3. Diff Tool
    4. Assuming Unchanged
    5. Resetting Commits
    6. Logs & Graphs
    7. Checking out & Branching
    8. Pulling & Rebasing
    9. Git SVN Commands
    10. Alias Master Command
    11. All in One

Basics

While creating a shortcut, we will be using the command alias. To create an alias in git, the complete syntax is:

git config [--global] alias.alias_name git_command  

For example, if you want to cut short git status to git s, you need to issue this command:

git config --global alias.s status  

Note that in the above command, there’s a flag --global, which makes the shortcut available for all the git repositories. If that’s not given, the shortcut will be applied only to the current repository and it will be stored in .gitconfig and not anywhere else.

Bonus: Wanna know where all git stores its configuration? have a look at Best way to import or export the Git Configuration. I have included a simple demonstration of where all git would store the configuration and consolidate them and uses it in your repository. It’s kinda like CSS — cascaded rules.

Well, instead of using the above command git config, I would strongly recommend developers to use the other command:

git config --edit --global  

This will open up a text editor and you can safely put stuff inside. When you open with or without the --global keyword, you will be shown a configuration file. You have to place all the aliases under the [alias] section with a tab or four space front of each shortcut.

Shortcuts

I have grouped the shortcuts into sub-sections, where you can find all the related shortcuts grouped by its similarity in functions.

  1. Basic Status & Adding
  2. Adding & Committing
  3. Diff Tool
  4. Assuming Unchanged
  5. Resetting Commits
  6. Logs & Graphs
  7. Checking out & Branching
  8. Pulling & Rebasing
  9. Git SVN Commands
  10. Alias Master Command
  11. All in One

Copy only those you need.

Basic Status & Adding

The following commands are the basic ones that are used often. They are used to check the status of the current working directory, adding all the files, displaying the status, etc.

[alias]
    s    = status
    a    = !git add . && git status
    au   = !git add -u . && git status
    aa   = !git add . && git add -u . && git status

Adding & Committing

These commands are used for adding the unstaged files, staging them, and then committing them too. The acm shortcut is a complete one, which will also allow you to add a commit message on the line and complete the commit. Please use the ca or --amend flag along with commit with caution. It’s really dangerous when you use it during merging or when pulling and before committing at least once.

[alias]
    ac   = !git add . && git commit
    acm  = !git add . && git commit -m
    c    = commit
    ca   = commit --amend # Be careful with this one.
    cm   = commit -m
    uc   = !git reset --soft HEAD^ && git reset HEAD .

Diff Tool

These commands are used to see what has changed. The --cached flag is used when you have already staged the changes for commit and you haven’t committed yet.

[alias]
    d    = diff
    dc   = diff --cached

Assuming Unchanged

This is a problem I faced when I committed the file and changed it. This is because, even though you have added the file in the .gitignore, git keeps a track of that file always other than in the situation you explicitly tell git to ignore it for a reason. To do this, what I did was I told git to assume that the file is always unchanged. This will remove the file from the list of tracked files. Any changes to this file will be untracked. This is for git to temporarily ignore the changes to a particular file.

git update-index --no-assume-unchanged <file / file pattern>  

In the above command, the <file / file pattern> denotes a single file like the above config.js or a file pattern like say secret/*. If we are going to use this command frequently, it is better we create an alias for these two commands. One best way to do is to edit the global config file using git config --global --edit and add the aliases as shown below:

[alias]
    hide = update-index --assume-unchanged
    unhide = update-index --no-assume-unchanged

Examples

git hide secret.txt      # File stays committed in the repo, but will not be tracked.  
git unhide secret.txt    # File will be tracked normally.  

Resetting Commits

Use with caution. These are the commands that remove your current changes that aren’t committed. This doesn’t mean the unsaved changes, but also those that are saved will be lost. Again, use with caution.

[alias]
    rh   = reset HEAD
    rha  = reset --hard
    rhh  = reset --hard HEAD

Logs & Graphs

If you wanna see the commit log, here they are. Some are used for displaying pretty graphs, which I had discussed in Git Standards followed in our way of Spotify Agile Methodology.

[alias]
    l    = log --graph --all --pretty=format:'%C(yellow)%h%C(cyan)%d%Creset %s %C(white)- %an, %ar%Creset'
    lg   = log --color --graph --pretty=format:'%C(bold white)%h%Creset -%C(bold green)%d%Creset %s %C(bold green)(%cr)%Creset %C(bold blue)<%an>%Creset' --abbrev-commit --date=relative
    ll   = log --stat --abbrev-commit
    llg  = log --color --graph --pretty=format:'%C(bold white)%H %d%Creset%n%s%n%+b%C(bold blue)%an <%ae>%Creset %C(bold green)%cr (%ci)' --abbrev-commit

Checking out & Branching

These commands are used for checking out to a new branch, checking out to another branch, creating branch from an existing branch, deleting branch, etc.

[alias]
    co   = checkout
    com  = checkout master
    cob  = checkout -b
    cod  = checkout development
    b    = branch
    bd   = branch -D

Examples

git co development  
git com  
git cob new-feature-branch  
git b  
git bd old-feature-branch  

Pulling & Rebasing

The following commands are for pushing, pulling, pulling and rebasing.

[alias]
    p    = pull
    po   = pull origin
    pom  = pull origin master
    pr   = pull --rebase
    pro  = pull --rebase origin
    prod = pull --rebase origin development
    ps   = push
    pu   = push -u
    puo  = push -u origin

Git SVN Commands

These commands are used in conjunction with SVN.

[alias]
    spl = svn rebase
    sps = svn dcommit

Alias Master Command

This command is kinda the «master» / «boss» command that shows all the aliases that you have currently have. This is like the meta-alias! 😜

[alias]
    alias = !git config --list | grep 'alias\\.' | sed 's/alias\\.\\([^=]*\\)=\\(.*\\)/\\1\\\t => \\2/' | sort

Usage: git alias.

All in One

The below one contains all the above shortcuts in a single [alias] section. Use really with caution:

[alias]
    s    = status
    a    = !git add . && git status
    au   = !git add -u . && git status
    aa   = !git add . && git add -u . && git status

    ac   = !git add . && git commit
    acm  = !git add . && git commit -m
    c    = commit
    ca   = commit --amend # Be careful with this one.
    cm   = commit -m
    uc   = !git reset --soft HEAD^ && git reset HEAD .

    d    = diff
    dc   = diff --cached

    hide = update-index --assume-unchanged
    unhide = update-index --no-assume-unchanged

    rh   = reset HEAD
    rha  = reset --hard
    rhh  = reset --hard HEAD

    l    = log --graph --all --pretty=format:'%C(yellow)%h%C(cyan)%d%Creset %s %C(white)- %an, %ar%Creset'
    lg   = log --color --graph --pretty=format:'%C(bold white)%h%Creset -%C(bold green)%d%Creset %s %C(bold green)(%cr)%Creset %C(bold blue)<%an>%Creset' --abbrev-commit --date=relative
    ll   = log --stat --abbrev-commit
    llg  = log --color --graph --pretty=format:'%C(bold white)%H %d%Creset%n%s%n%+b%C(bold blue)%an <%ae>%Creset %C(bold green)%cr (%ci)' --abbrev-commit

    co   = checkout
    com  = checkout master
    cob  = checkout -b
    cod  = checkout development
    b    = branch
    bd   = branch -D

    p    = pull
    po   = pull origin
    pom  = pull origin master
    pr   = pull --rebase
    pro  = pull --rebase origin
    prod = pull --rebase origin development
    ps   = push
    pu   = push -u
    puo  = push -u origin

    spl = svn rebase
    sps = svn dcommit

    alias = !git config --list | grep 'alias\\.' | sed 's/alias\\.\\([^=]*\\)=\\(.*\\)/\\1\\\t => \\2/' | sort

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Windows приложения для командной строки
  • Play old windows games online
  • Менеджер печати windows 7
  • Google chrome com windows 7
  • Файл windows system32 config system код ошибки 0xc0000185