How to input password to git pull command?

2020-05-20 07:22发布

问题:

I have written scripts for Windows and Linux to essentially set up a new users workspace with all the git repositories from our server.

I would like the user to enter the password for our server once, store it in a local variable, pass that variable to each git pull command, then erase the password variable and exit.

How can I input the password when the git pull command requests it? Both for Windows batch file and a Linux shell script.

Here is code from the Linux script:

#!/bin/bash

echo "Enter password: "
read pswd
clear #No screen peaking

#This is repeated for each repo
location=folderName
mkdir $location
cd $location
git init
git remote add origin git@<server>:$location.git
git pull origin master 
#Above prompts for password & is where I want to automatically input $pswd

I've tried various things recommended on SO and elsewhere, such as piping, reading from .txt file, etc. I would prefer to not need anything more than plain old windows cmd and Linux terminal commands. And as this script is just for set up purposes, I do not need to securely store the password permanently with something like ssh agent.

I'm running Windows 7 and Ubuntu 12.10, but this script is meant for setting up new users, so it should ideally work on most distributions.

回答1:

I would really recommend to not try and manage that password step, and delegate that (both on Linux and Windows) to git credential helper.
See:

  • "Git http - securely remember credentials"
  • "How to use git with gnome-keyring integration"

The user will enter the password only once per session.



回答2:

Synopsis:

git pull "https://<username>:<password>@github.com/<github_account>/<repository_name>.git" <branch_name>

Example:

git pull "https://admin:12345@github.com/Jet/myProject.git" master

Note: This works for me on a bash script



回答3:

Read the remote url from git and then insert the ID and password (PW) to the url might work.

For example try the following:

cd ${REPOSITORY_DIR}
origin=$(git remote get-url origin)
origin_with_pass=${origin/"//"/"//${USER_ID}:${USER_PW}@"}
git pull ${origin_with_pass} master