Languages
[Edit]
EN

Bash - clone git repository providing username and password directly when running (as command option or in URL)

9 points
Created by:
elmer
646

In this short article, we would like to show how to clone git repository providing username and password when running using Bash.

Quick solution:

git clone https://username:password@github.com/username/repository.git

Hint: do not forget to encode username and password when they contains URLs special characters. 

 

Possible cases

password is optional in URL syntax, so by using:

git clone https://username@github.com/username/repository.git

we will be asked to type password while command is executed.

 

Practical example

In practice username and password should be encoded. In this section you can find JavaScript's encodeURIComponent() function equivalent.

#!/bin/bash

function create_utf8_code() {
	local code="$(echo -n "$1" | xxd -ps)"
	local length="${#code}"
	local i
	for (( i = 0; i < length; i += 2 ))
	do
		echo -n "%${code:$i:2}" | tr '[:lower:]' '[:upper:]'
	done
}

function encode_uri_component() {
	local text="${1}"
	local length="${#text}"
	local i char
	for (( i = 0; i < length; ++i ))
	do
		char="${text:$i:1}"
		[[ "$char" =~ [-_.!~*\'()a-zA-Z0-9] ]] && echo -n "$char" || create_utf8_code "$char"
	done
}


encoded_username="$(encode_uri_component "username")"
encoded_password="$(encode_uri_component "P@$$word")"

git clone "https://$encoded_username:$encoded_password@github.com/username/repository.git"

 

See also

  1. Bash - JavaScript encodeURIComponent equivalent

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join