Первоначальная настройка Git
Теперь, когда Git установлен в вашей системе, самое время настроить среду для работы с Git под себя.
Это нужно сделать только один раз — при обновлении версии Git настройки сохранятся.
Но, при необходимости, вы можете поменять их в любой момент, выполнив те же команды снова.
В состав Git входит утилита git config
, которая позволяет просматривать и настраивать параметры, контролирующие все аспекты работы Git, а также его внешний вид.
Эти параметры могут быть сохранены в трёх местах:
-
Файл
[path]/etc/gitconfig
содержит значения, общие для всех пользователей системы и для всех их репозиториев.
Если при запускеgit config
указать параметр--system
, то параметры будут читаться и сохраняться именно в этот файл.
Так как этот файл является системным, то вам потребуются права суперпользователя для внесения изменений в него. -
Файл
~/.gitconfig
или~/.config/git/config
хранит настройки конкретного пользователя.
Этот файл используется при указании параметра--global
и применяется ко всем репозиториям, с которыми вы работаете в текущей системе. -
Файл
config
в каталоге Git (т. е..git/config
) репозитория, который вы используете в данный момент, хранит настройки конкретного репозитория.
Вы можете заставить Git читать и писать в этот файл с помощью параметра--local
, но на самом деле это значение по умолчанию.
Неудивительно, что вам нужно находиться где-то в репозитории Git, чтобы эта опция работала правильно.
Настройки на каждом следующем уровне подменяют настройки из предыдущих уровней, то есть значения в .git/config
перекрывают соответствующие значения в [path]/etc/gitconfig
.
В системах семейства Windows Git ищет файл .gitconfig
в каталоге $HOME
(C:\Users\$USER
для большинства пользователей).
Кроме того, Git ищет файл [path]/etc/gitconfig
, но уже относительно корневого каталога MSys, который находится там, куда вы решили установить Git при запуске инсталлятора.
Если вы используете Git для Windows версии 2.х или новее, то так же обрабатывается файл конфигурации уровня системы, который имеет путь C:\Documents and Settings\All Users\Application Data\Git\config
в Windows XP или C:\ProgramData\Git\config
в Windows Vista и новее.
Этот файл может быть изменён только командой git config -f <file>
, запущенной с правами администратора.
Чтобы посмотреть все установленные настройки и узнать где именно они заданы, используйте команду:
$ git config --list --show-origin
Имя пользователя
Первое, что вам следует сделать после установки Git — указать ваше имя и адрес электронной почты.
Это важно, потому что каждый коммит в Git содержит эту информацию, и она включена в коммиты, передаваемые вами, и не может быть далее изменена:
$ git config --global user.name "John Doe"
$ git config --global user.email johndoe@example.com
Опять же, если указана опция --global
, то эти настройки достаточно сделать только один раз, поскольку в этом случае Git будет использовать эти данные для всего, что вы делаете в этой системе.
Если для каких-то отдельных проектов вы хотите указать другое имя или электронную почту, можно выполнить эту же команду без параметра --global
в каталоге с нужным проектом.
Многие GUI-инструменты предлагают сделать это при первом запуске.
Выбор редактора
Теперь, когда вы указали своё имя, самое время выбрать текстовый редактор, который будет использоваться, если будет нужно набрать сообщение в Git.
По умолчанию Git использует стандартный редактор вашей системы, которым обычно является Vim.
Если вы хотите использовать другой текстовый редактор, например, Emacs, можно проделать следующее:
$ git config --global core.editor emacs
В системе Windows следует указывать полный путь к исполняемому файлу при установке другого текстового редактора по умолчанию.
Пути могут отличаться в зависимости от того, как работает инсталлятор.
В случае с Notepad++, популярным редактором, скорее всего вы захотите установить 32-битную версию, так как 64-битная версия ещё не поддерживает все плагины.
Если у вас 32-битная Windows или 64-битный редактор с 64-битной системой, то выполните следующее:
$ git config --global core.editor "'C:/Program Files/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"
Примечание |
Vim, Emacs и Notepad++ — популярные текстовые редакторы, которые часто используются разработчиками как в Unix-подобных системах, таких как Linux и Mac, так и в Windows. |
Предупреждение |
В случае, если вы не установили свой редактор и не знакомы с Vim или Emacs, вы можете попасть в затруднительное положение, когда какой-либо из них будет запущен. |
Настройка ветки по умолчанию
Когда вы инициализируете репозиторий командой git init
, Git создаёт ветку с именем master по умолчанию.
Начиная с версии 2.28, вы можете задать другое имя для создания ветки по умолчанию.
Например, чтобы установить имя main для вашей ветки по умолчанию, выполните следующую команду:
$ git config --global init.defaultBranch main
Проверка настроек
Если вы хотите проверить используемую конфигурацию, можете использовать команду git config --list
, чтобы показать все настройки, которые Git найдёт:
$ git config --list
user.name=John Doe
user.email=johndoe@example.com
color.status=auto
color.branch=auto
color.interactive=auto
color.diff=auto
...
Некоторые ключи (названия) настроек могут отображаться несколько раз, потому что Git читает настройки из разных файлов (например, из /etc/gitconfig
и ~/.gitconfig
).
В таком случае Git использует последнее значение для каждого ключа.
Также вы можете проверить значение конкретного ключа, выполнив git config <key>
:
$ git config user.name
John Doe
Примечание |
Так как Git читает значение настроек из нескольких файлов, возможна ситуация когда Git использует не то значение, которое вы ожидали.
|
Last Updated :
27 May, 2024
Git is a powerful version control system that allows developers to track changes in their codebase efficiently. It comes with a variety of configuration options that can be set globally (for all repositories) or locally (for a specific repository). Viewing your global Git configuration helps you understand and manage settings that apply across all your Git projects. This article will guide you through the process of displaying your global Git configuration.
Table of Content
- What is Git Configuration?
- Steps to Show Global Git Configuration
- Understanding Common Configuration Settings
- Modifying Global Configuration Settings
- Viewing All Levels of Configuration
- Conclusion
What is Git Configuration?
Git configuration involves setting preferences that control how Git operates and manages repositories. These settings include user information, text editor preferences, merge and diff tools, and various behaviours for Git commands. Configurations can be set at three levels:
- System Level: Applies to all users on a system.
- Global Level: Applies to the current user across all repositories.
- Local Level: Applies only to a specific repository.
This article focuses on viewing global configurations.
Steps to Show Global Git Configuration
To view your global Git configuration, you can use the git config
command with specific flags that tell Git to show configuration settings.
Step 1: Open Your Terminal
Open the terminal or command prompt on your system. You can use any terminal emulator of your choice, such as Git Bash on Windows, Terminal on macOS, or a terminal emulator on Linux.
Step 2: Run the Command to View Global Configuration
Use the following command to display all global configuration settings
git config --global --list
This command will output a list of all global configuration settings and their values. For example:
Step 3: View Specific Configuration Settings
If you want to view a specific configuration setting, you can specify the key. For example, to view the global user email configuration, run
git config --global user.email
This command will output the value of the user.email
setting.
Understanding Common Configuration Settings
Here are some common global configuration settings you might see:
- user.name: Your name, used for commits.
- user.email: Your email address, used for commits.
- core.editor: The default text editor for Git commands.
- color.ui: Controls the use of color in Git output.
- alias.: Shortcuts for Git commands (e.g.,
alias.co=checkout
).
Modifying Global Configuration Settings
If you need to change any of your global configuration settings, you can use the git config --global
command followed by the key and value you want to set. For example, to change your global user name
git config --global user.name "Sagar Agarwal"
To change your global user email:
git config --global user.email "sagar@example.com"
Viewing All Levels of Configuration
If you want to see the configuration settings at all levels (system, global, and local), you can use the --list
flag without specifying --global
git config --list
This command will display settings from the system, global, and local configuration files. Note that local settings can override global and system settings.
Conclusion
Viewing your global Git configuration is a straightforward process that helps you manage and verify settings applied across all your repositories. By using the git config --global --list
command, you can easily see all global configurations. This is useful for ensuring your Git environment is set up correctly and consistently. If needed, you can also modify these settings to better suit your workflow. Understanding and managing your Git configuration is essential for efficient and error-free version control.
The git config
command is used for setting and querying various Git configuration options. These options control various aspects of Git’s operation and look, including user information, editor preferences, repository-specific settings, and more.
This guide covers common use cases of the git config
command.
Configuring username and email with git config
Before you start committing in Git, it’s essential to set up your username and email address since every Git commit uses this information.
-
Set Global Username and Email:
git config --global user.name "Your Name" git config --global user.email "your_email@example.com"
-
git config --global user.name "Your Name"
: sets the name that will be attached to your commits and tags as the author. «Your Name» should be replaced with your actual name or the name you wish to appear in your commits. The--global
flag means this setting is applied across all Git repositories on your computer, for the current user. If you make a commit, Git records this name as the author of the commit. -
git config --global user.email "your_email@example.com"
: sets your email address for all your Git repositories on your computer. «your_email@example.com» should be replaced with your actual email address. This email is used in commits you make, and it’s important for services like GitHub, GitLab, or Bitbucket to link your commits to your account on these platforms.
-
-
Set username and email for a specific repository: You can also set these fields per repository. To do this, navigate to your repository directory and run:
git config user.name "Your Name" git config user.email "your_email@example.com"
Without the
--global
flag,git config
only affects the local configuration of the repository you are currently in. This allows for repository-specific settings that override the global configurations for that specific repository.
Listing and showing configurations
-
List all configurations:
git config --list
When you run the
git config --list
command in your console or terminal, Git will display all the configuration settings that are currently set for your Git installation, including local, global, and system configurations. Here’s an example of what the output might look like:
user.name=Your Name
user.email=your_email@example.com
core.repositoryformatversion=0
core.filemode=true
core.bare=false
core.logallrefupdates=true
core.ignorecase=true
remote.origin.url=https://github.com/username/repository.git
remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
branch.main.remote=origin
branch.main.merge=refs/heads/main
commit.template=/path/to/commit_template.txt
merge.tool=vimdiff
diff.tool=vimdiff
core.editor=nano
alias.co=checkout
alias.br=branch
alias.ci=commit
alias.st=status
color.ui=true
color.status=auto
color.branch=auto
credential.helper=cache --timeout=3600
This output shows a mix of global and local settings:
-
user.name
anduser.email
are globally set user identification settings for commits. -
core.repositoryformatversion
,core.filemode
,core.bare
, and others are internal settings for the repository. -
remote.origin.url
andremote.origin.fetch
specify the URL of the remote repository named «origin» and how branches are fetched from it. -
branch.main.remote
andbranch.main.merge
configure the default upstream branch for the local main branch. -
commit.template
points to a file that Git will use as the default message template for commits. -
merge.tool
anddiff.tool
specify the tools to use for merging and diffing. -
core.editor
defines the default text editor for Git operations that require one. -
alias
entries show custom shortcuts for common Git commands. -
color.ui
,color.status
, andcolor.branch
are preferences for colored output in Git commands. -
credential.helper
configures Git to cache your password for a limited time.
While the exact output will vary based on your configuration settings, this command is useful for verifying current configurations or diagnosing unexpected Git behaviors.
-
Show specific configuration: You can also check specific configurations by passing in a specific field as an argument to the
git config
command:git config user.name
For example, this command will output the currently configured username.
Configuration levels
Git config works at three levels: local, global, and system.
Local Configuration (--local
)
-
Scope: Local configuration applies only to a specific repository. Each repository on your system can have a unique local configuration. Local configurations take precedence, and override global configurations.
-
Use cases: Use local configurations for settings that should only apply to a specific project, such as project-specific user names, email addresses, merge strategies, or Git hooks.
-
Location: These settings are stored in the
.git/config
file within the repository’s directory. -
Example: This command sets Vim as the editor for this particular repository.
git config --local core.editor vim
Global configuration (--global
)
-
Scope: Global configuration affects all the repositories used by the current user on the machine. It allows you to define settings that you want to apply across your projects.
-
Use cases: Ideal for settings like your user name and email, which are likely to be consistent across all your Git activities. Also used for defining global ignore patterns and setting up aliases you want available in every project.
-
Location: These settings are stored in a
.gitconfig
file located in the user’s home directory (~/.gitconfig
on Unix-like systems andC:\\\\Users\\\\USERNAME\\\\.gitconfig
on Windows). -
Example: This sets your email address for all your repositories.
git config --global user.email "your_email@example.com"
System configuration (--system
)
-
Scope: System configuration is applied across all users on the current computer. This level is typically used for settings that should be universal across all projects and users on the machine.
-
Use cases: System-level configurations might include settings related to system-wide Git behavior, security configurations, or network settings. This is particularly useful in organizational contexts where many users operate on the same system.
-
Location: The configuration file for system-level settings varies by operating system. On Unix-like systems, it’s often located at
/etc/gitconfig
. On Windows, it might be found inC:\\\\ProgramData\\\\Git\\\\config
. -
Command example: This example disables automatic conversion of line endings for every user on the system.
sudo git config --system core.autocrlf false
Prioritization of configurations
Git prioritizes configurations at the local level over the global level, and global over system, meaning that if the same configuration is specified at multiple levels, the more specific level takes precedence. For example, a user.email
setting in the local configuration of a repository will override the global configuration.
Best practices
-
Use local for project-specific settings: Customize behavior for individual projects without affecting your global setup.
-
Leverage global for personal defaults: Set your identity and preferences that you want to apply across all your projects.
-
Reserve system for universal settings: Administrators can set configurations that apply to all users, useful in managed or shared environments.
Understanding and utilizing these three levels of configuration allows for a highly customizable and efficient Git workflow, tailored to the needs of individual projects, users, and entire systems.
Editing config files directly
-
To edit system configuration run:
git config --system --edit
-
To edit global configuration run:
git config --global --edit
-
To edit local configuration run:
git config --edit
The default text editor for git config
can be set using:
git config --global core.editor "editor_name"
Configuration file locations
-
Global configuration file location:
-
Linux/Mac:
~/.gitconfig
-
Windows:
C:\\\\Users\\\\USERNAME\\\\.gitconfig
-
-
System configuration file location:
-
Linux/Mac:
/etc/gitconfig
-
Windows:
C:\\\\ProgramData\\\\Git\\\\config
-
-
Local configuration file location: Inside the repository:
.git/config
Tips for Effective Configuration
-
Always ensure your user name and email are correctly set before starting to work in a new environment.
-
Use the
-global
flag for settings that you want to apply across all your projects. -
Repository-specific settings (local) can override global settings. Use this feature to customize behavior per project.
-
Regularly review your configuration using
git config --list
to ensure it matches your current setup and preferences.
For further reading on Git configuration, see the official Git documentation.
Git stores configuration data in three different scopes: local, global and system.
Using the git config
command we can list all Git config settings as well as only local, global or system settings.
For each scope, Git stores settings in different config files and it may be useful to know how to locate those files.
In this note i am showing how to list Git config settings and how to find Git config files location.
Cool Tip: Save username & password in Git credentials store! Read more →
List all Git configuration settings:
$ git config --list
Show the location of Git config files where these settings are defined:
git config --list --show-origin
Separately list global, local and system configuration settings:
$ git config --list --local $ git config --list --global $ git config --list --system
Was it useful? Share this post with the world!
# Setting which editor to use
There are several ways to set which editor to use for committing, rebasing, etc.
For one command:
Or for all commands run in a terminal. Note: This only applies until you close the terminal.
Note: As above, this only applies to the current terminal; your shell will usually have a configuration file to allow you to set it permanently. (On bash
, for example, add the above line to your ~/.bashrc
or ~/.bash_profile
.)
Some text editors (mostly GUI ones) will only run one instance at a time, and generally quit if you already have an instance of them open. If this is the case for your text editor, Git will print the message Aborting commit due to empty commit message.
without allowing you to edit the commit message first. If this happens to you, consult your text editor’s documentation to see if it has a --wait
flag (or similar) that will make it pause until the document is closed.
# Auto correct typos
This enables autocorrect in git and will forgive you for your minor mistakes (e.g. git stats
instead of git status
). The parameter you supply to help.autocorrect
determines how long the system should wait, in tenths of a second, before automatically applying the autocorrected command. In the command above, 17 means that git should wait 1.7 seconds before applying the autocorrected command.
However, bigger mistakes will be considered as missing commands, so typing something like git testingit
would result in testingit is not a git command.
# Username and email address
Right after you install Git, the first thing you should do is set your username and email address. From a shell, type:
git config
is the command to get or set options--global
means that the configuration file specific to your user account will be editeduser.name
anduser.email
are the keys for the configuration variables;user
is the section of the configuration file.name
andemail
are the names of the variables."Mr. Bean"
andmrbean@example.com
are the values that you’re storing in the two variables. Note the quotes around"Mr. Bean"
, which are required because the value you are storing contains a space.
# Multiple git configurations
You have up to 5 sources for git configuration:
-
— **`%ALLUSERSPROFILE%\Git\Config`** (Windows only)
- (system) **`/etc/gitconfig`**, with « being the git installation path.
(on Windows, it is **`\mingw64\etc\gitconfig`**) - The order is depended, the last one who matches «wins».
- the
/
at the end is needed — e.g."gitdir:D:/work"
won’t work. - the
gitdir:
prefix is required. - git config [] name [value] # one of the more common use cases of git config
— (system) **`$XDG_CONFIG_HOME/git/config`** (Linux/Mac only)
— (global) `~/.gitconfig` (Windows: `%USERPROFILE%\.gitconfig`)
— (local) `.git/config` (within a git repo `$GIT_DIR`)
— a **dedicated file** (with `git config -f`), used for instance to modify the config of submodules: `git config -f .gitmodules …`
The order is important: any config set in one source can be overridden by a source listed below it.
git config --system/global/local
is the command to list 3 of those sources, but only git config -l would list all resolved configs.
«resolved» means it lists only the final overridden config value.
Since git 2.8, if you want to see which config comes from which file, you type:
# List and edit the current configuration
Git config allows you to customize how git works. It is commonly used to set your name and email or favorite editor or how merges should be done.
To see the current configuration.
To edit the config:
If you intend the change to be true for all your repositories, use --global
You can list again to see your changes.
# Multiple usernames and email address
Since Git 2.13, multiple usernames and email addresses could be configured by using a folder filter.
# Example for Windows:
# .gitconfig
Edit: git config --global -e
Add:
# .gitconfig-work.config
File in the same directory as .gitconfig
# .gitconfig-opensource.config
File in the same directory as .gitconfig
# Example for Linux
The file content and notes under section Windows.
# Configuring line endings
# Description
When working with a team who uses different operating systems (OS) across the project, sometimes you may run into trouble when dealing with line endings.
# Microsoft Windows
When working on Microsoft Windows operating system (OS), the line endings are normally of form — carriage return + line feed (CR+LF). Opening a file which has been edited using Unix machine such as Linux or OSX may cause trouble, making it seem that text has no line endings at all. This is due to the fact that Unix systems apply different line-endings of form line feeds (LF) only.
In order to fix this you can run following instruction
On checkout, This instruction will ensure line-endings are configured in accordance with Microsoft Windows OS (LF -> CR+LF)
# Unix Based (Linux/OSX)
Similarly, there might be issues when the user on Unix based OS tries to read files which have been edited on Microsoft Windows OS. In order to prevent any unexpected issues run
On commit, this will change line-endings from CR+LF -> +LF
# configuration for one command only
you can use -c <name>=<value>
to add a configuration only for one command.
To commit as an other user without having to change your settings in .gitconfig :
Note: for that example you don’t need to precise both user.name
and user.email
, git will complete the missing information from the previous commits.
# Setup a proxy
If you are behind a proxy, you have to tell git about it:
If you are no more behind a proxy:
# Syntax
# Parameters
Parameter | Details |
---|---|
--system |
Edits the system-wide configuration file, which is used for every user (on Linux, this file is located at $(prefix)/etc/gitconfig ) |
--global |
Edits the global configuration file, which is used for every repository you work on (on Linux, this file is located at ~/.gitconfig |
--local |
Edits the respository-specific configuration file, which is located at .git/config in your repository; this is the default setting |