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:


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?

$ sed -e "s^//^//$user:$pass@^" <<<$uri

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

In Bash specifically:

$ echo ${uri/\/\////$user:$pass@}

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.

  • 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.