我可以在环境变量中保存 git 凭据吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8536732/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I hold git credentials in environment variables?
提问by Jon Cram
I'd like to create a very simple shell script, which will ultimately be called by another application, that updates a local git repository:
我想创建一个非常简单的 shell 脚本,它最终将由另一个应用程序调用,它更新本地 git 存储库:
#!/bin/bash
cd
sudo git pull
When executing this I'm asked for credentials (I'm pulling from a private BitBucket repository).
执行此操作时,我被要求提供凭据(我从私有 BitBucket 存储库中提取)。
Can I ( briefly) store credentials in environment variables?
我可以(简要地)将凭据存储在环境变量中吗?
#!/bin/bash
export GIT_USERNAME=<user>
export GIT_PASSWORD=<pass>
cd
sudo git pull
The above doesn't work. Would anything? I could programmatically modify the origin url but that seems a bit execessive.
以上是行不通的。会什么吗?我可以以编程方式修改原始 url,但这似乎有点过分。
回答by Patryk ?ciborek
I know that it's very old question but if you really need to pass username and password for HTTP basic authentication you can just set helper like this:
我知道这是一个很老的问题,但如果你真的需要为 HTTP 基本身份验证传递用户名和密码,你可以像这样设置 helper:
git config credential.helper '!f() { sleep 1; echo "username=${GIT_USER}"; echo "password=${GIT_PASSWORD}"; }; f'
UPDATE: I've added sleep 1
to the function. In some environments it may be probably needed due to race condition. I've got 2 virtual machines running Debian Jessie. They had the same architecture but different CPU and different number of cores. On one of these machines the helper was working fine without sleep
. On the other one it wasn't. After few hours of debugging I run strace
to see what's happening. And it magically started to work. strace
just made git a little bit slower.
更新:我已添加sleep 1
到该功能中。在某些环境中,由于竞争条件,可能需要它。我有 2 台运行 Debian Jessie 的虚拟机。它们具有相同的架构,但不同的 CPU 和不同数量的内核。在其中一台机器上,助手在没有sleep
. 在另一处不是。经过几个小时的调试后,我跑去strace
看发生了什么。它神奇地开始工作。strace
只是让 git 慢了一点。
回答by Mike Dotterer
You can set the username in the git config with:
您可以使用以下命令在 git config 中设置用户名:
git config credential.https://github.com.username $GIT_USER
Then you can set the GIT_ASKPASS
environment variable to a script that will provide the password:
然后您可以将GIT_ASKPASS
环境变量设置为将提供密码的脚本:
export GIT_ASKPASS=/path/to/git_env_password.sh
The contents of git_env_password.sh
would be:
的内容git_env_password.sh
将是:
#!/bin/bash
echo $GIT_PASSWORD
N.B: This will store the username in the git config, so if you are not okay with that use another solution.
注意:这会将用户名存储在 git config 中,因此如果您对此不满意,请使用其他解决方案。
For more info consult the gitcredentials man page.
有关更多信息,请参阅gitcredentials 手册页。