I have weird problem with Git bash. I have two Github accounts, let’s say A and B. I set my name and email, like in account A:
git config --global user.name
git config --global user.email
I initialized new repo, did a commit, then push and git bash
asked me about login and password to github. By mistake I put login and password for account B! I logged in successfully, but there is no repository I just initialized.
How can I logout and login to different github account? It’s not user.name
nor user.email
Jason Aller
3,50728 gold badges42 silver badges38 bronze badges
asked Jan 17, 2017 at 5:03
8
Much simpler, as I explained in «How to sign out in Git Bash console in Windows?»:
git credential-manager erase <url>
Here
git credential-manager erase https://github.com
No need to remove the credential helper which is practical for caching user’s password.
Or (replace xxx wit the output of git config --global credential.helper
):
printf "protocol=httpsnhost=github.com" | git-credential-xxx erase
# Windows (2020-2021)
printf "protocol=httpsnhost=github.com" | git-credential-manager-core erase
# Linux
printf "protocol=httpsnhost=github.com" | git-credential-libsecret erase
# MacOs
printf "protocol=httpsnhost=github.com" | git-credential-osxkeychain erase
answered Jan 17, 2017 at 5:36
VonCVonC
1.2m508 gold badges4248 silver badges5069 bronze badges
1
My situation is I had change my gitlab.com’s account email, then my local git repository can not push. saTya ‘s answer worked, but in windows 10 1903, it is Control Panel -> Credential Manager -> Windows Credentials -> Generic Credentials.
answered Aug 28, 2019 at 9:19
leolmqleolmq
1911 silver badge6 bronze badges
In windows search for Manage window credentials
This window will get opened
in that look into generic credentials for git login, Then remove it by expanding it and pressing remove. After try to push your code via git bash, it will automatically ask you to login.so you can login with your another account. hope its helpful.
answered Oct 13, 2020 at 7:23
AravinthAravinth
851 silver badge2 bronze badges
If you’re already connect to any github account after some time you went to pull or push some other repository which belong to some other account.
Example:
I have already connected or my github account username and password is verifed which is «account@gmail.com» it work and find everything is okay, but if I want another directory which is belong to some other account. as I pull it. gitbash generates an error «your required repository is not found». It was actually due to connecting your gitbash to an old account. First of all you have to remove all old credentials and add a new account. Then it will work fine.
Example:
to remove old credentials, use this command
git credential-manager delete https://github.com
and add again username user name and email
git config user.name = "new_username"
git config user.email= "newEmail@gmail.com"
after the verification push or pull you repository
git pull -u origin master
Then it will work fine and your code will push or pull from a remote repository which belongs to other account.
answered Jun 19, 2020 at 15:45
1
Change username and email global
git config --global user.name "<username>"
git config --global user.email "<email>"
Change username and email for current repo
git config user.name "<username>" --replace-all
git config user.email "<email>" --replace-all
answered Oct 31, 2020 at 22:50
PurgoufrPurgoufr
71513 silver badges22 bronze badges
1
One solution: change SSH key.
At the Begin, I have an account A.
Then, I have a ssh key on ~/.ssh/id_rsa.pub
. I add this key to GitHub ssh key list https://github.com/settings/keys.
When I try to push commit to GitHub in CLI, the GitHub will know who I am.
Now, I want to switch my git account for GitHub. I just add transfer ~/.ssh/id_rsa.pub
to my account B in GitHub settings.
After this, when I try to push to GitHub, GitHub will think I am B.
answered Mar 2, 2019 at 11:11
bytefishbytefish
2,3163 gold badges20 silver badges34 bronze badges
I have two github accounts. One for hobby one for work.
I generated another ssh key for work: ~/.ssh/.id_rsa_work.pub
then add it to my work account: https://github.com/jack
.
In my ~/.ssh/config
, now I added this for work account:
Host github-work
HostName github.com
IdentityFile ~/.ssh/id_rsa_work
Then when I want to clone from company repo git@github.com:company_org_name/company_repo_name.git
,
I run(note the github-work
part):
$ git clone git@github-work:company_org_name/company_repo_name.git
That’s it.
Don’t forget to set local name and email for company repo right after you run git clone
.
git config user.name "my name at company"
git config user.email "my email at company"
Now you have multiple accounts on your device. You won’t feel any difference from now on.
answered Jun 12, 2022 at 7:36
shrekuushrekuu
1,4261 gold badge20 silver badges37 bronze badges
git credentials will be searched for ~/.git-credentials
or ~/.config/git/credentials
files. You can search these files and if found then modify it.
$ git config --global --unset credential.helper
# search file
$ sudo find / -type f -name .git-credentials
$ sudo find / -type f -name credentials
For Windows, manager
stores your credentials. It has a Control Panel Interface
where you can edit or delete
your stored credential.
$ git config --global credential.helper manager
answered Jan 17, 2017 at 5:15
Sajib KhanSajib Khan
21.9k8 gold badges63 silver badges72 bronze badges
3
If you are not able to clone from repo saying git clone getting remote repository not found even if the repo exist in git bash.
Here you just need to delete the old credential and then try to access the repo with proper repo account access credentials.
git credential-manager delete https://github.com
( deleteing old credential)
In repo url add <username>@
before github.com
git clone --branch https://<username>@github.com/abhinav/myproj.git
Now you will get a login popup so provide the credentials
Then cloning will be performed successfully.
answered Aug 4, 2020 at 7:39
abhinav kumarabhinav kumar
1,4371 gold badge11 silver badges20 bronze badges
i had similar problem at «intellegy IDEA», in it’s terminal , spent 2 hours, but only need to do: intelliIDEA->references (for Mac IDEA) or file->settings (for windows) to choose gitHub delete account, add new (it can have problems too, in browser need to came in decired account) press apply
answered Nov 3, 2022 at 23:48
I have weird problem with Git bash. I have two Github accounts, let’s say A and B. I set my name and email, like in account A:
git config --global user.name
git config --global user.email
I initialized new repo, did a commit, then push and git bash
asked me about login and password to github. By mistake I put login and password for account B! I logged in successfully, but there is no repository I just initialized.
How can I logout and login to different github account? It’s not user.name
nor user.email
Jason Aller
3,50728 gold badges42 silver badges38 bronze badges
asked Jan 17, 2017 at 5:03
8
Much simpler, as I explained in «How to sign out in Git Bash console in Windows?»:
git credential-manager erase <url>
Here
git credential-manager erase https://github.com
No need to remove the credential helper which is practical for caching user’s password.
Or (replace xxx wit the output of git config --global credential.helper
):
printf "protocol=httpsnhost=github.com" | git-credential-xxx erase
# Windows (2020-2021)
printf "protocol=httpsnhost=github.com" | git-credential-manager-core erase
# Linux
printf "protocol=httpsnhost=github.com" | git-credential-libsecret erase
# MacOs
printf "protocol=httpsnhost=github.com" | git-credential-osxkeychain erase
answered Jan 17, 2017 at 5:36
VonCVonC
1.2m508 gold badges4248 silver badges5069 bronze badges
1
My situation is I had change my gitlab.com’s account email, then my local git repository can not push. saTya ‘s answer worked, but in windows 10 1903, it is Control Panel -> Credential Manager -> Windows Credentials -> Generic Credentials.
answered Aug 28, 2019 at 9:19
leolmqleolmq
1911 silver badge6 bronze badges
In windows search for Manage window credentials
This window will get opened
in that look into generic credentials for git login, Then remove it by expanding it and pressing remove. After try to push your code via git bash, it will automatically ask you to login.so you can login with your another account. hope its helpful.
answered Oct 13, 2020 at 7:23
AravinthAravinth
851 silver badge2 bronze badges
If you’re already connect to any github account after some time you went to pull or push some other repository which belong to some other account.
Example:
I have already connected or my github account username and password is verifed which is «account@gmail.com» it work and find everything is okay, but if I want another directory which is belong to some other account. as I pull it. gitbash generates an error «your required repository is not found». It was actually due to connecting your gitbash to an old account. First of all you have to remove all old credentials and add a new account. Then it will work fine.
Example:
to remove old credentials, use this command
git credential-manager delete https://github.com
and add again username user name and email
git config user.name = "new_username"
git config user.email= "newEmail@gmail.com"
after the verification push or pull you repository
git pull -u origin master
Then it will work fine and your code will push or pull from a remote repository which belongs to other account.
answered Jun 19, 2020 at 15:45
1
Change username and email global
git config --global user.name "<username>"
git config --global user.email "<email>"
Change username and email for current repo
git config user.name "<username>" --replace-all
git config user.email "<email>" --replace-all
answered Oct 31, 2020 at 22:50
PurgoufrPurgoufr
71513 silver badges22 bronze badges
1
One solution: change SSH key.
At the Begin, I have an account A.
Then, I have a ssh key on ~/.ssh/id_rsa.pub
. I add this key to GitHub ssh key list https://github.com/settings/keys.
When I try to push commit to GitHub in CLI, the GitHub will know who I am.
Now, I want to switch my git account for GitHub. I just add transfer ~/.ssh/id_rsa.pub
to my account B in GitHub settings.
After this, when I try to push to GitHub, GitHub will think I am B.
answered Mar 2, 2019 at 11:11
bytefishbytefish
2,3163 gold badges20 silver badges34 bronze badges
I have two github accounts. One for hobby one for work.
I generated another ssh key for work: ~/.ssh/.id_rsa_work.pub
then add it to my work account: https://github.com/jack
.
In my ~/.ssh/config
, now I added this for work account:
Host github-work
HostName github.com
IdentityFile ~/.ssh/id_rsa_work
Then when I want to clone from company repo git@github.com:company_org_name/company_repo_name.git
,
I run(note the github-work
part):
$ git clone git@github-work:company_org_name/company_repo_name.git
That’s it.
Don’t forget to set local name and email for company repo right after you run git clone
.
git config user.name "my name at company"
git config user.email "my email at company"
Now you have multiple accounts on your device. You won’t feel any difference from now on.
answered Jun 12, 2022 at 7:36
shrekuushrekuu
1,4261 gold badge20 silver badges37 bronze badges
git credentials will be searched for ~/.git-credentials
or ~/.config/git/credentials
files. You can search these files and if found then modify it.
$ git config --global --unset credential.helper
# search file
$ sudo find / -type f -name .git-credentials
$ sudo find / -type f -name credentials
For Windows, manager
stores your credentials. It has a Control Panel Interface
where you can edit or delete
your stored credential.
$ git config --global credential.helper manager
answered Jan 17, 2017 at 5:15
Sajib KhanSajib Khan
21.9k8 gold badges63 silver badges72 bronze badges
3
If you are not able to clone from repo saying git clone getting remote repository not found even if the repo exist in git bash.
Here you just need to delete the old credential and then try to access the repo with proper repo account access credentials.
git credential-manager delete https://github.com
( deleteing old credential)
In repo url add <username>@
before github.com
git clone --branch https://<username>@github.com/abhinav/myproj.git
Now you will get a login popup so provide the credentials
Then cloning will be performed successfully.
answered Aug 4, 2020 at 7:39
abhinav kumarabhinav kumar
1,4371 gold badge11 silver badges20 bronze badges
i had similar problem at «intellegy IDEA», in it’s terminal , spent 2 hours, but only need to do: intelliIDEA->references (for Mac IDEA) or file->settings (for windows) to choose gitHub delete account, add new (it can have problems too, in browser need to came in decired account) press apply
answered Nov 3, 2022 at 23:48
Первоначальная настройка 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 SettingsAll UsersApplication DataGitconfig
в Windows XP или C:ProgramDataGitconfig
в 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 использует не то значение что вы ожидали.
|
Git is an open-source version control system. Git is software that helps to track updates in any folder. It is a DevOps resource used mostly for source code planning. It’s typically used to promote collaboration between coders who are relying on source code together during software development. Speed, the integrity of data, including support for dispersed, non-linear workflows are among the aims.
A terminal Git environment is handled by Git Bash (Bash, an acronym for Bourne Again Shell). Git Bash replicates a bash terminal on Windows. It allows you to use all git tools or most other typical Unix commands from the command line. If you’re used to Linux and want to preserve your routines, this is a great alternative.
Git is usually bundled as one of the elevated GUI applications in Windows settings. Bash is a popular Linux and Mac OS default shell. On a Windows operating system, Git Bash is a package that installs Bash, some standard bash utilities, and Git. The fundamental version control system primitives may be abstracted and hidden by Git’s GUI. Git Bash is a Microsoft Windows software that functions as an abstraction shell for the Git command-line experience. A shell is a console application that allows you to interact with your operating system by command prompt.
Now let us discuss how to set Git Username and Password in Git Bash
Step 1: After the successful installation of Git on your system, you have to right-click wherever you want to open the Git tab. Click on the Git Bash Here icon. Now here we will see the location of where the program is opened when the window opens.
Git Bash opened on Desktop.
Step 2: In the Git Bash window, type the below command and press enter. This will configure your Username in Git Bash.
$ git config --global user.name "GeeksforGeeks"
Step 3: After that, you will have to configure your email. For that, type
$git config --global user.email "GFGexample@gmail.orgg"
Step 4: To set your password, type the below command as depicted:
$git config --global user.password "1234321"
Step 5: To save the credentials forever, type the below command as depicted:
$ git config --global credential.helper store
This is how you set git username and password in git bash.
To check the inputs, type the below command as depicted:
git config --list --show-origin
После того, как мы установили Git, пришло время внести некоторые изменения в конфигурационный файл Git и настроить учетные данные с помощью Git Bash.
Когда мы устанавливаем Git в нашей системе, конфигурационный файл принимает значения по умолчанию для некоторых полей. Это означает, что Git начинает с установки одинаковых файлов для каждого пользователя. Таким образом, при первом запуске Git общие файлы по умолчанию (которые являются общими для каждого пользователя) ищутся внутри файла /etc/gitconfig.
После того, как они установлены, Git должен видеть файлы, относящиеся к конкретному пользователю. Эти конкретные файлы доступны в разделе ~/.gitconfig или ~/.config/git/config. Конкретный файл включает в себя ваше имя пользователя, ваше имя и т. д.
Откройте свой Git Bash и введите следующую команду, чтобы просмотреть личные настройки конфигурации.
vi ~/.gitconfig
Нажмите enter и просмотрите файл конфигурации.
Пример
Давайте рассмотрим пример, чтобы понять, почему нам нужно настроить эти значения во время работы в проекте. Многие люди работают над одним проектом, но единственное, что может идентифицировать вас, — это ваше имя пользователя или адрес электронной почты. Если вы не настроили эти значения в файле конфигурации, эти значения (имя, адрес электронной почты и т. д.) берутся случайным образом. Поэтому, когда вы совершаете какое-либо изменение, это изменение отражается вместе с вашим именем пользователя и электронной почтой, которые являются случайными, и никто не сможет распознать или запомнить ваши учетные данные. Это создает много проблем в команде. Следовательно, мы должны изменить этот конфигурационный файл.
Как настроить учетные данные по умолчанию для git Config?
Задайте имя пользователя в конфигурации Git
Первое изменение, которое мы сделаем внутри нашего конфигурационного файла, будет изменение нашего имени пользователя в Git. Чтобы изменить имя пользователя, выполните следующие действия.
Откройте Git Bash в вашей системе. Введите следующую команду с вашим именем пользователя:
git config --global user.name “Your UserName”
Примечание: изменение имени пользователя повлияет только на ваши будущие коммиты и ни на один из ваших прошлых коммитов.
Это изменит имя пользователя на значение, указанное в команде. Нажмите enter, и если ничего не произошло, имя было успешно изменено.
Настройка электронной почты пользователя в git Config
После успешного выполнения вышеуказанной команды мы изменим нашу электронную почту. Введите следующую команду
git config --global user.email “YourEmailID.com”
Это изменит идентификатор электронной почты в конфигурации Git на идентификатор электронной почты, указанный в команде.
Как просмотреть список пользовательских настроек git Config?
После того, как вы установили все значения в файле конфигурации, вы можете просмотреть все настройки также через Git Bash.
Просмотреть полный список настроек в git Config
Для этого перейдите в Git Bash и введите эту команду.
git config --list
Нажмите enter, и вы увидите все настройки, включая те, которые мы только что установили в предыдущем разделе.

Просмотр определенного параметра в конфигурации Git
Вы также можете проверить наличие определенного параметра в файле конфигурации вместо того, чтобы открывать полный список. Чтобы увидеть это, выполните следующие простые шаги.
В Git Bash введите следующую команду:
git config --global <key>
здесь <key> относится к имени параметра, который вы хотите видеть. Например user.name. Вам нужно запомнить значение ключа именно таким, как оно есть. Если вы не можете вспомнить, то всегда можете отобразить полный список конфигурационных файлов.
Нажмите клавишу enter, чтобы увидеть значение ключа.
https://git-scm.com/docs/git-config — больше информации о git-config.
#git #github #permissions
Изначально тренировался пользоваться гитом на аккаунте DeleteMePl, в последствии зарегистрировался нормально и склонировал (Clone with HTTPS) новый проект на ПК (Windows 7). При попытке что-ли отправить на клонированный репозиторий получаю следующую ошибку: $ git push remote: Permission to Пользователь/Web.git denied to DeleteMePl. fatal: unable to access 'https://github.com/Пользователь/Web.git/': The requested URL returned error: 403 Github определяет меня, как старого пользователя DeleteMePl. Когда тренировался с гитхабом, он спрашивал у меня (первый раз) логин и пароль. Вопрос: где он их сохранил и как их удалить? Временное решение: Пришлось открыть себе доступ через аутентификацию по ключу ssh (https://help.github.com/articles/generating-an-ssh-key). Хотя всё работает, но меня продолжает тревожить то, что я на свой аккаунт должен получать разрешение, а не входить по логину и паролю. Решение описал ниже в ответе: https://ru.stackoverflow.com/a/624219/226239
Ответы
Ответ 1
по поводу кэша данных при http-авторизации возможно, вам всего лишь надо очистить кэш данных для http-авторизации: $ git credential-cache exit по поводу url fatal: unable to access 'https://github.com/Пользователь/Web.git/': The requested URL returned error: 403 это весьма похоже на url отдалённого хранилища. скорее всего, у вас в локальном хранилище подключено всего одно отдалённое хранилище, и, скорее всего, под псевдонимом origin. посмотреть его (url) можно, например, такой командой: $ git config remote.origin.url изменить — аналогично: $ git config remote.origin.url новое_значение_url или отредактируйте любым удобным вам редактором файл .git/config (каталог .git находится в каталоге с вашим проектом), секцию [remote "origin"]: ... [remote "origin"] ... url = это самое значение
Ответ 2
Решение найдено: Необходимо зайти в: Панель управленияУчетные записи пользователей и семейная безопасностьДиспетчер учетных данных в разделе: "общие учетные данные" удалить учётку для git. Выглядит она так: git:https://github.com При следующем взаимодействии в консоле, git попросит ввести логин и пароль в отдельном окне авторизации.
Ответ 3
В Windows 10: Control PanelAll Control Panel ItemsCredential Manager Выбрать Windows Credential Удалить или изменить соответствующий git:http ...