Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a script to perform git pull?

It is a common practice to perform git pull on dev/staging/production server(s). I frequently do so myself; I perform git pull almost 100 times a day on my production server running linux.

I figure, it's time to make a script to improve that.


pull.sh will do these 3 commands

  • git pull
  • enter my-password (when prompt)
  • service nginx reload

I've tried create my pull.sh here

#!/bin/bash

function pull {
  git pull
  password
  service nginx reload
}


pull ;

Result

After running the script that I have, I still got prompt to input the password.

enter image description here


Any hints / helps / suggestions will be much appreciated !

like image 630
code-8 Avatar asked Dec 19 '22 23:12

code-8


2 Answers

You can use expect script to interact with git authentication:

#!/usr/bin/expect -f
spawn git pull
expect "ass"
send "your_password\r"
interact

It waits for "ass" text (that matches "Password", "password", "passphrase") and then it sends your password.

That script can be called from another bash script that will restart your server:

# Call script directly since the shell knows that it should run it with
# expect tool because of the first script line "#!/usr/bin/expect -f"
./git-pull-helper-script.sh
# Without the first line "#!/usr/bin/expect -f" the file with commands
# may be sent explicitly to 'expect':
expect file-with-commands

# Restart server
service nginx reload
like image 81
Orest Hera Avatar answered Dec 30 '22 15:12

Orest Hera


The way to handle a passphrase is to use an ssh agent: that way, you only need to type in your passphrase once.

I have this in my dev user's ~/.bash_profile

# launch an ssh agent at login, so git commands don't need to prompt for password
# ref: http://stackoverflow.com/a/18915067/7552

SSH_ENV=$HOME/.ssh/env

if [[ -f ~/.ssh/id_rsa ]]; then
    function start_agent {
        # Initialising new SSH agent...
        ssh-agent | sed 's/^echo/#&/' > "${SSH_ENV}"
        chmod 600 "${SSH_ENV}"
        source "${SSH_ENV}" > /dev/null
        ssh-add
    }

    # Source SSH settings, if applicable

    if [ -f "${SSH_ENV}" ]; then
        source "${SSH_ENV}" > /dev/null
        agent_pid=$(pgrep ssh-agent)
        (( ${agent_pid:-0} == $SSH_AGENT_PID )) || start_agent
        unset agent_pid
    else
        start_agent
    fi
fi
like image 33
glenn jackman Avatar answered Dec 30 '22 15:12

glenn jackman