douglaslps
douglaslps

Reputation: 8168

Shell script self update using git

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.

Upvotes: 5

Views: 6248

Answers (1)

douglaslps
douglaslps

Reputation: 8168

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

Upvotes: 12

Related Questions