Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shell script self update using git

Tags:

git

bash

shell

I'm writing a script to execute tasks before my end to end tests. One of the steps is to select the branch where those tests were written. Sometimes the script changes between different branches so I need the script to update itself before the actual execution.

Is it possible for a bash script in my git repository to update itself and execute the new version only?

In summary: When I execute script.sh I want it to check git if a new version is available and if so, download this new version and execute it while the old version simply dies.

like image 319
douglaslps Avatar asked Feb 12 '16 15:02

douglaslps


1 Answers

This is the script I came up with:

#!/bin/bash

SCRIPT=$(readlink -f "$0")
SCRIPTPATH=$(dirname "$SCRIPT")
SCRIPTNAME="$0"
ARGS="$@"
BRANCH="Your_git_branch"

self_update() {
    cd $SCRIPTPATH
    git fetch

    [ -n $(git diff --name-only origin/$BRANCH | grep $SCRIPTNAME) ] && {
        echo "Found a new version of me, updating myself..."
        git pull --force
        git checkout $BRANCH
        git pull --force
        echo "Running the new version..."
        exec "$SCRIPTNAME" "$@"

        # Now exit this old instance
        exit 1
    }
    echo "Already the latest version."
}

main() {
   echo "Running"
}

self_update
main
like image 50
douglaslps Avatar answered Oct 07 '22 16:10

douglaslps