2

I need to insert user credentials into an HTTP string so I can properly populate my git credentials file at ~/.git-credentials.

These are the three environment variables I have to start with:

user="someUser"
pass="somePass"
uri="http://sometld.org/path/repo.git"

I've been fiddling with awk, but it will only work with Github style cloning paths (https://github.com/org/repo.git) and won't work with non-standard paths (https://git.private.org/scm/~user/path/repo.git):

proto=$(echo $uri | awk -F"/" '{print $1}')
domain=$(echo $uri | awk -F"/" '{print $3}')
repo_path=$(echo $uri | awk -F"/" '{print $4}')
repo_name=$(echo $uri | awk -F"/" '{print $5}')
echo "$proto//$user:$pass@$domain/$repo_path/$repo_name"
# http://someUser:somePass@sometld.org/path/repo.git

What is the best/easiest way to insert a username and password into an HTTP string so I can populate my ~/.git-credentials file?

3
$ sed -e "s^//^//$user:$pass@^" <<<$uri
http://someUser:somePass@sometld.org/path/repo.git

This replaces // with //$user:$pass@ in the string $uri and will work anywhere.

In Bash specifically:

$ echo ${uri/\/\////$user:$pass@}
http://someUser:somePass@sometld.org/path/repo.git

will perform the same replacement - this is just ${variable/pattern/replacement}, but it's necessary to escape the slashes in the pattern because we can't change the delimiters here.

1
  • Oh, that is a brilliant way to do it. Perfect, thanks!
    – SiennaD.
    Apr 10 '18 at 2:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.