Куда записывается git config — global?
при использовании git config —global чтобы настроить вещи, в какой файл он будет писать?
Я не могу найти его в этих местах:
Я не установил ENV?
моя версия Git: 1.6.5.1.1367.gcd48 – на Windows 7
14 ответов:
обновление 2016: с git 2.8 (март 2016), вы можете просто использовать:
вы увидите, какая конфигурация установлена где.
Смотрите «откуда берутся настройки в моей конфигурации Git?»
он будет работать с нестандартной установки. (т. е. Git Portable)
(как последний PortableGit-2.14.2-64-bit.7z.exe , который может быть распакован в любом месте вы хотите)
оригинальный ответ (2010)
— global
для параметров записи: запись в global
/.gitconfig файл, а не репозиторий .git/config .
так как вы используете Git для Windows, это может быть не ясно, какое место это соответствует. Но если вы посмотрите на etc / профиль (in C:\Program Files\Git ), вы увидите:
это означает, что файл находится в C:\Users\MyLogin\.gitconfig для Git в Windows 7.
Я тоже искал глобальный .gitconfig на моей машине Windows и нашел этот аккуратный трюк с помощью git.
Do a: git config —global -e и тогда, если Вам повезет, вы получите текстовый редактор, загруженный с вашим глобальным . Просто найдите папку оттуда (или попробуйте сохранить как. ), и вуаля! : -)
/.gitconfig . Есть ли соответствующий файл в вашем доме?
в Windows вы можете ввести git bash
Windows XP — C:\Documents and Settings\ \.gitconfig
Windows Vista+ C:\Users\ \.gitconfig
глобальное расположение выводится в Windows MsysGit с помощью переменных среды HOMEDRIVE и HOMEPATH, если не определена переменная среды HOME. Это подробно описано в сценарии «профиль».
в моей корпоративной среде HOMEDRIVE — это H:, который затем сопоставляется с сетевым URL \\share\$. Вся партия затем отображается как «Мои документы», что не там, где ожидали бы другие. Возможно, были некоторые дополнительные проблемы с переадресацией диска на URL. Я даже не буду в любом случае регулировать ДИСК_ДОМАШНЕЙ_ПАПКИ или переменные HOMEPATH.
в моем случае я определил личную переменную домашней среды и указал на нее D:\git\GitHOME и скопировал все эти файлы GIT (которые без и расширения) в каталог GitHOME для безопасного хранения.
переменные среды windows можно задать на вкладке Дополнительно в диалоговом окне Свойства моего компьютера.
Если вы используете TortoiseGit на ПК с windows, вы можете использовать:
открыть глобальный .файла.gitignore
но если вы используете свой ПК с Windows (7) в домене, ваш профиль dir может быть сетевым ресурсом (установленным как диск). В этом случае TortoiseGit (по крайней мере:1.6.5.0) указывает вам на неправильный dir (на c. ). Смотрите закрытый TortoiseGit проблема 922 для получения дополнительной информации. Или с помощью %HOMEDRIVE% % HOMEPATH% открыть каталог, содержащий .файла.gitignore
Я использую SmartGit С msysgit на Windows 8.1 и заметил, что есть три различных места для gitconfig file:
но тот, который используется, является одним из » C:\Users\name\.gitconfig «.
может быть полезно отметить (для платформ *nix): некоторые типы глобальной конфигурации/информации git хранятся в /usr/share/git-core/ , такие как сценарии автозаполнения git и следующие (по умолчанию) крючки:
- applypatch-msg
- после обновления
- pre-commit
- prepare-commit-msg
- commit-msg
- pre-applypatch
- pre-rebase
- обновление
каждый из них может содержать их собственный набор команд для выполнения, в то время как описываются их соответствующие имена файлов.
вы можете найти его с помощью следующей команды
Я запускаю Windows 7 и использую git в качестве установки, следуя инструкциям на GitHub (год или два назад). Довольно распространенный прецедент, я бы подумал. Ни один из ответов выше не помог мне, и после большого разочарования я в конечном итоге нашел свой «реальный» файл gitconfig в следующем каталоге;
очевидно, заменить имя пользователя и предположительно суффикс после PortableGit_-это уникальный идентификатор GUID или аналогичный.
у меня также была проблема с моим глобальным .gitconfig Это для случая, когда у кого-то также есть этот странный
fatal: неизвестная ошибка произошла при чтении файлов конфигурации
теперь я исправил это. Проблема была во втором .gitconfig в этой папке:
Я не знаю, откуда он взялся. Но теперь все работает как шарм снова.
когда-глобальная .создан файл gitconfig?
во-первых, git не создает автоматически глобальный конфигурационный файл (.gitconfig) во время его установки. Файл не создается до тех пор, пока он не будет записан в первый раз. если вы никогда не устанавливали системную переменную, ее не будет в вашей файловой системе. Я предполагаю, что может быть источником проблемы.
один из способов попросить Git создать его-запросить редактирование. Это сила создание файла.
git config —global —edit
Если вы контролируете домашнюю папку пользователя при выполнении этой команды ,вы увидите.файл gitconfig волшебным образом появляется.
где хранится конфигурация git?
вот краткое изложение имени и местоположения файлов конфигурации, связанных с тремя областями Git, а именно система,глобальные и local:
- конфигурация System Git: файл с именем gitconfig расположенном в -ГИТ-установка-расположение/мин/и т. д.
- глобальная конфигурация Git: файл с именем .gitconfig находится в домашней папке пользователя (пользователь c:\users\git )
- локальная конфигурация Git: файл с именем config на .git folder локального РЕПО
конечно, видеть-значит верить, поэтому вот изображение, показывающее каждый файл и каждое местоположение. Я вытащил изображение из статьи, которую я написал по этой теме.
удалите Msysgit и установите Cygwin + Git. Тогда глобальный ‘.gitconfig ‘ будет здесь: C:\cygwin (64)\home\[имя пользователя]\.gitconfig .
теперь вам не нужно беспокоиться о переменной среды, которая может быть использована другими программами. Например, моя переменная среды указала мне на подключенный диск в моей рабочей среде домена windows. Я не хочу, чтобы мой глобальный .gitconfig сидит на моем» домашнем » подключенном диске. Я также не знаю, что может случиться с другими приложениями, которые могут полагаться это переменная среды windows. Отделу операций может потребоваться, чтобы эта переменная среды была установлена на подключенный диск по какой-либо причине.
Также вам не придется беспокоиться о Mysysgit перезаписи параметров конфигурации «профиль», если вы укажете конкретный путь к глобальному».gitconfig’, используя этот метод.
В общем, сохраните себя и используйте Cygwin bash shell в windows и будьте счастливее
у меня была похожая проблема, проблема была в том, что .gitconfig файл был расположен в
другими словами, файл был расположен в C:\Users\MyLogin\.gitconfig\.gitconfig , вместо C:\Users\MyLogin\.gitconfig (именно там Git искал файлы).
Where to find system, global and local Git config files on Windows and Ubuntu Linux
Community driven content discussing all aspects of software development from DevOps to design patterns.
- 5 Steps to Alleviate Endpoint Management Tool Sprawl –HCL Technologies Limited India
- 3 Security Best Practices for CI/CD –CircleCI
One of the five basic Git commands beginners need to learn is git config , if for no other reason than to perform an initial commit without the Git tool pestering for a user.name and user.email address. But the git config command commonly used to initialize these fields typically employs a global switch, which gets users wondering about Git’s competing local and system scopes.
That then leads to the question about where all of these variously scoped Linux and Windows git configuration files can be found. Here we will answer all of those questions about Git config file locations and where the various gitconfig files are stored.
Full list of where the Git configuration files config, gitconfig and .gitconfig are located on Windows and Ubuntu Linux.
Listed in descending order of specificity, Git provides four standard scopes for storing configuration data, plus a portable scope on Windows:
Note: You will notice a ‘portable scope’ mentioned in the Windows Git config table above. This scope was pointed out to me by a reader after this article first published. The portable scope is the most general and is overridden by all other scopes.
The scopes are cascading with the most specific file taking precedence over the most general. Local scope overrides global scope. Global scope overrides system scope.
If you set up multiple Git worktrees on the same computer, you can also use the Git worktree scope, although doing so requires this scope to be enabled. Worktree scope is the most specific and will override local.
Just to make life a bit more complicated, the variously scoped Git configuration files all have different names:
- gitconfig – the extensionless system Git config file
- .gitconfig – the global Git config file has no name, but is instead just an extension
- config – the local Git configuration file is simply named config, and like the system Git config file, has no extension
- config.worktree – the Git worktree configuration file flaunts both a name and an extension
Here is where you will find Git configuration files on Windows:
Location of Windows Git Config Files | ||
---|---|---|
Scope | Location and Filename | Filename Only |
System | \mingw64\etc\gitconfig | gitconfig |
Global | C:\Users\username\.gitconfig | .gitconfig |
Local | \.git\config | config |
Worktree | \.git\config.worktree | config.worktree |
Portable | C:\ProgramData\Git\config | config |
As for the location of the Linux Git configuration files, here is where you’ll find them on Ubuntu:
Ubuntu Linux Git Config File Locations | ||
---|---|---|
Scope | Location and Filename | Filename Only |
System | gitconfig | |
Global | .gitconfig | |
Local | /.git/config | config |
Worktree | /.git/config.worktree | config.worktree |
To find the Git config file setting a given variable to a particular value, the –list and –show-origin switches of the git command can be useful. In the following example you can see the command indicating that the user.email property is set in the portable, system, local and global scopes. It also states exactly where those files Git config files are located.
Here is the git config command with list and show-origin swtiches run on Windows:
Here is the same command run on Ubnutu where the Git user.name property is set in three separate scopes:
On StackOverflow, the following command was suggested to help developers find the location of the Git config files:
The animated GIF below, pulled from 1998 when such things were cool, shows the above command being run on Ubuntu 20. Note how the command above lists the home directory as the location for the global Git config file, but when the sudo command is used below the global Git config file is in
Git config file locations on Ubuntu Linux.
Sometimes users go looking for the global and system Git config files and can’t find them. If you can’t find gitconfig or .gitconfig, it’s probably because it’s not there.
Git doesn’t actually create the gitconfig or .gitconfig files until they are referenced for the first time. Just asking Git to edit the file will force its creation, but until that happens, efforts to find the .gitconfig or gitconfig file will be fruitless.
The following operation will likely require sudo rights on a Linux distribution as you may be creating files in privileged \etc or \root directories. But when run with elevated permissions, these commands are sufficient enough to force the creation of global and system gitconfig and .gitconfig files:
Each of these Git commands will open the corresponding Windows or Linux Git config file in the configuration specified editor. You may edit the file if you please, or simply close the editor immediately to force config file creation.
Figure 2. The three main locations of Windows Git configuration files.
On the topic of editors, if you’d like to switch the Git editor to Notepad++, just issue the following command:
Always be careful editing the Git config files, because if you incorrectly edit any of these files, you just might ruin your entire Linux or Windows Git configuration.
Want to become a powerful Git user? Then take a look at the following Git articles and tutorials: