NickC
NickC

Reputation: 35

Bash Script that uses Git to Update Only Itself

I have a bash script that gets updated fairly often that I would like to have self-update only itself using git, but not affect anything else.

I found an Example Script that updates itself, but it uses git pull --force which updates everything. Most of the time this should be fine, but I hesitate to automatically do something with the potential to have unintended consequences, safer to just affect only itself.

My attempts to modify that script to use checkout or cherry-pick have not been successful.

Does anyone have a function that updates only $0 or can write one?

Edit: This is the messy code I wrote for my script.

#!/bin/bash


BRANCH="master"
SCRIPTNAME=$1
REPOSITORY="https://stash.xxx/projects/IT/repos/xxx/browse/$SCRIPTNAME"

self_update() {

git fetch

if  [[ -n $(git diff --name-only origin/$BRANCH | grep $SCRIPTNAME) ]]
then
echo The version you have and the version on stash are different
echo
echo Do you want to:
echo
echo s. Show messy differences
echo c. Open repository in Chrome
echo
echo d. Download the stash version, overwrite your current version, and exit script
echo
echo q. return to the previous menu

read choice
case $choice in
s)
git diff origin/$BRANCH
echo
read -p "Enter to Return " enterkey
;;
c)
open -a "/Applications/Google Chrome.app"  "$REPOSITORY"
;;
d)
git checkout -f origin/$BRANCH -- $SCRIPTNAME

#head -5 $SCRIPTNAME
exit
;;
q)
break
;;
*)
echo Please enter one of the choices.
;;
esac

else
echo You are using the current version of $SCRIPTNAME
break
fi

}


#testing code
head -5 $SCRIPTNAME

while :
do
self_update
done

head -5 $SCRIPTNAME

Upvotes: 1

Views: 372

Answers (2)

Jesús M. Navarro
Jesús M. Navarro

Reputation: 420

A "dumb" approach: git clone to a different (temp) path, copy to the desired location and delete the temp path.

...or else, have it permanently checked-out and just pull/fetch. In this case, you most possibly will want that path to be declared within .gitignore in the main repo.

Upvotes: 0

eftshift0
eftshift0

Reputation: 30317

Checkout should work

git fetch the-remote
git checkout  the-remote/the-branch -- the-file.sh

This better not run on windows because it will reject rewrite the script while it's running.

Upvotes: 1

Related Questions