EN
Bash - clone git repository providing username and password directly when running (as command option or in URL)
9
points
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
usernameandpasswordwhen 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"