我正在尝试自动化包含一系列 git 命令的过程。
我希望 shell 脚本处理一些交互式命令,比如将用户名和密码传递给 git clone url -v
.我验证了如果我只是运行 git clone url -v
它将按顺序显示以下内容:
- 克隆到 someRepo
- 询问用户名
- 询问密码
我试过:
-
echo -e 'username\n' | git clone url -v
-
echo -e 'username\npassword\n' | git clone url -v
-
git clone url -v <<< username\npassword\n
-
(sleep 5;echo -e 'username\n' | git clone url -v)
我以为第一条消息cloning into repo
需要一些时间。它们都不起作用,但它们都显示相同的消息 Username for url:
在这方面花了很多时间,我知道
git clone https://$username:$password@enterpriseGithub.com/org/repo
正在工作,但使用它是不安全的,因为日志明确显示了用户名和密码。
最佳答案
更好的做法是完全避免用户/密码身份验证(如通过配置基于代理的身份验证,理想情况下由存储在物理 token 上的私钥支持),或在 keystore 中设置凭据存储由您的操作系统提供(并希望得到保护)——但如果您只想将凭据保留在命令行之外,则可以这样做:
# Assume that we already know the credentials we want to store...
gitUsername="some"; gitPassword="values"
# Create a file containing the credentials readable only to the current user
mkdir -p "$HOME/.git-creds/https"
chmod 700 "$HOME/.git-creds"
cat >"$HOME/.git-creds/https/enterprise-github.com" <<EOF
username=$gitUsername
password=$gitPassword
EOF
# Generate a script that can retrieve stored credentials
mkdir -p -- "$HOME/bin"
cat >"$HOME/bin/git-retrieve-creds" <<'EOF'
#!/usr/bin/env bash
declare -A args=( )
while IFS= read -r line; do
case $line in
*..*) echo "ERROR: Invalid request" >&2; exit 1;;
*=*) args[${line%%=*}]=${line#*=} ;;
'') break ;;
esac
done
[[ ${args[protocol]} && ${args[host]} ]] || {
echo "Did not retrieve protocol and host" >&2; exit 1;
}
f="$HOME/.git-creds/${args[protocol]}/${args[host]}"
[[ -s $f ]] && cat -- "$f"
EOF
chmod +x "$HOME/bin/git-retrieve-creds"
# And configure git to use that
git config --global credential.helper "$HOME/bin/git-retrieve-creds"
关于linux - 用于克隆 GitHub 存储库的 Shell 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53673848/