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:[email protected]/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?

1 Answer 1

4
$ sed -e "s^//^//$user:$pass@^" <<<$uri
http://someUser:[email protected]/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:[email protected]/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!
    – Sienna
    Commented Apr 10, 2018 at 2:16

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .