首页 > 解决方案 > 用于克隆 GitHub 存储库的 Shell 脚本

问题描述

我正在尝试自动化一个包含一系列 git 命令的过程。

我希望 shell 脚本处理一些交互式命令,比如将用户名和密码传递给git clone url -v. 我验证如果我只是运行git clone url -v它会按顺序显示以下内容:

  1. 克隆到 someRepo
  2. 询问用户名
  3. 询问密码

我试过了:

  1. echo -e 'username\n' | git clone url -v
  2. echo -e 'username\npassword\n' | git clone url -v
  3. git clone url -v <<< username\npassword\n
  4. (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

正在工作,但使用它是不安全的,因为日志明确显示了用户名和密码。

标签: linuxbashgitshellcommand-line

解决方案


更好的做法是完全避免用户/密码身份验证例如通过配置基于代理的身份验证,理想情况下由存储在物理令牌上的私钥支持),或者在操作系统提供(并希望保护)的密钥库中设置凭证存储-- 但如果您只想将凭据保留在命令行之外,可以这样做:

# 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"

推荐阅读