Saturday, January 27, 2024

[SOLVED] Bash Script that uses Git to Update Only Itself

Issue

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 href="https://stackoverflow.com/questions/35365799/shell-script-self-update-using-git">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


Solution

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.



Answered By - eftshift0
Answer Checked By - Dawn Plyler (WPSolving Volunteer)