乐闻世界logo
搜索文章和话题

How can i save username and password in git?

3个答案

1
2
3

You can enable credential storage in Git using git config.

shell
git config --global credential.helper store

When you run this command, the system will prompt you for your username and password the first time you pull or push from a remote repository.

Subsequently, for subsequent communication with the remote repository, you do not need to provide your username and password.

The credentials are stored in the .git-credentials file in plaintext format.

Additionally, you can use other helpers like git config credential.helper for memory caching:

shell
git config credential.helper 'cache --timeout=<timeout>'

It requires an optional timeout parameter that determines how long credentials are retained in memory. With this helper, credentials never touch the disk and are deleted after the specified timeout. The default value is 900 seconds (15 minutes).

Warning: If you use this method, your Git account password will be stored in plaintext in the global .gitconfig file, for example, at /home/[username]/.gitconfig on Linux.

If you do not wish to do this, use an SSH key instead for your account.

2024年6月29日 12:07 回复

You can edit the ~/.gitconfig file to store your credentials:

bash
nano ~/.gitconfig

which should already contain

ini
[user] email = your@email.com user = gitUSER

You should add the following at the bottom of this file.

ini
[credential] helper = store

I recommend this option because it is global, and if you ever need to remove it, you know where to modify it.

Use this option only on your personal computer.

Then when you pull, clone, or enter your Git password, typically, the password is stored in the following format in ~/.git-credentials:

text
https://gituser:gitpassword@domain.xxx

Note that DOMAIN.XXX can be github.com, bitbucket.org, or others.

See the documentation at Git Credential Store.

Restart your terminal.

2024年6月29日 12:07 回复

Follow these steps to generate the key: More details

shell
$ ssh-keygen -t rsa -b 4096 -C "yourEmail@something.com"

Set a passphrase for the key and store it locally.

Copy the contents of the id_rsa.pub file to the clipboard for the next step.

shell
$ clip < ~/.ssh/id_rsa.pub

Navigate to github.com → Settings → SSH and GPG Keys → New SSH Key. Paste the key and save it.

If the private key is saved as id_rsa in the ~/.ssh/ directory, add it for authentication as follows:

shell
ssh-add -K ~/.ssh/id_rsa

A More Secure Method: Caching

We can use the git-credential-cache to cache our username and password for a period of time. Simply enter the following in the CLI (terminal or command prompt):

shell
git config --global credential.helper cache

You can also set the timeout (in seconds) as follows:

shell
git config --global credential.helper 'cache --timeout=3600'
2024年6月29日 12:07 回复

你的答案