bash script adding git credentials from bash script

13,668

Solution 1

For basic HTTP authentication you can:

  1. Pass credentials inside url:

    git clone http://USERNAME:PASSWORD@some_git_server.com/project.git
    

    WARN this is not secure: url with credentials can be seen by another user on your machine with ps or top utilities when you work with remote repo.

  2. Use gitcredentials:

    $ git config --global credential.helper store
    $ git clone http://some_git_server.com/project.git
    
    Username for 'http://some_git_server.com': <USERNAME>
    Password for 'https://USERNAME@some_git_server.com': <PASSWORD>
    
  3. Use ~/.netrc:

    cat >>~/.netrc <<EOF
    machine some_git_server.com
           login <USERNAME>
           password <PASSWORD>
    EOF
    

Solution 2

You can still pass in the username and password into the URL for git clone:

git clone https://username:[email protected]/username/repository.git

As for using a bash script, You can pass the username $1 and password $2:

git clone https://$1:[email protected]/username/repository.git

Then call the script with:

./script.sh username password

Addtionally, It might be more secure to leave the password out and only include the username:

git clone https://[email protected]/username/repository.git

Since the command with your password will be logged in your bash history. However, you can avoid this by adding a space in front of the command.

You can also use How do I parse command line arguments in Bash? for nicer ways to use command line arguments.

Also be careful to use URL Encoding for special characters in usernames and passwords. A good example of this is using %20 instead of @, since URLS need to use standard ASCII encoding for characters outside the standard character set.

Solution 3

1) This may help you add credentials git

2) I currently work with gitlab and I have it in a container with jenkins, anyway to do the clone I do this: http://<user_gitlab>@ip_gitlab_server/example.git

I hope I help you

Share:
13,668
0xsegfault
Author by

0xsegfault

Updated on June 12, 2022

Comments

  • 0xsegfault
    0xsegfault almost 2 years

    I need to be able to add git credentials from my to my bash script but can't figure out how to do this.

    git clone https://xxxxxxx
    

    would ask for my username name and password.

    how to i pass these in a bash script ?

    any pointers would be appreciated

    • Roland Puntaier
      Roland Puntaier over 2 years
      This answer contains a sample bash script.