Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MSYS shell keeping script file open, preventing modifications

Usually when running a shell script, the shell keeps the script file open throughout the execution. On Unix systems this is not a problem.

However, Windows prevents modifications to a file that is opened in that way. Which means that if a script is running in MSYS, I need to kill the shell before I can modify the script. This is annoying because git pull or svn up will fail.

I am looking for a solution to that problem, for instance through specific options I could put in the #!/bin/sh line, or some kind of shell one-liner that would maybe cause the script to copy itself in a safe place and execute the copy instead.

like image 720
sam hocevar Avatar asked Mar 13 '26 05:03

sam hocevar


1 Answers

You could let the script re-exec itself. Split it like this:

#!/bin/sh
if test -z "$MYSCRIPT_REEXEC"; then
    : stuff you do before git pull
    exec env MYSCRIPT_REEXEC=1 sh -c "git pull; . '$0'"
fi
: stuff you do after git pull

This is a simple case, $0 may not contain apostrophs, and the arguments and any variables set in the first half are inaccessible. It’s hard to give a better generic example – maybe, if I could see the original script?

If this still does not work, try this one:

#!/bin/sh
if test -z "$MYSCRIPT_REEXEC"; then
    : stuff you do before git pull
    env MYSCRIPT_REEXEC=1 sh -c "sleep 1; git pull; . '$0'" &
    exit 0
fi
: stuff you do after git pull

In this case, though, return codes will also be all wrong, as will anything waiting for the script.

like image 151
mirabilos Avatar answered Mar 15 '26 01:03

mirabilos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!