0

I'm implementing a batch file similar to the Gradle wrapper. The idea is that it will download the main application and run it, without the user having to download and install the application itself.

This is all working fine, and now I'm implementing updating the application. This involves replacing the batch file with a new version of the batch file (which has a new download URL in it, in addition to any changes to the batch file itself).

However, when my application replaces the batch file, this leads to weird results (as discussed in https://stackoverflow.com/a/31257641/1668119 and other answers in that question). Is there a safe way to replace a batch file while it is running that doesn't result in new or removed lines causing issues?

Charles
  • 155
  • 8
  • I guess this happens because Windows remembers the position of the last executed statement. Try to make room by adding spaces or newlines – Marged Jul 20 '19 at 08:48
  • 1
    But presumably it is a cleaner approach to create a second batch file and call it from the previous one – Marged Jul 20 '19 at 08:49
  • 2
    Yes, there is. Take a look on [this answer](https://stackoverflow.com/a/56949764/3074564) showing a method how a batch file copies itself temporarily to folder for temporary files to be able to do something on original batch file like deleting, editing or replacing it. – Mofi Jul 20 '19 at 08:58

1 Answers1

0

Based on Mofi's comment and the answer they linked to, I'm using something like this:

setlocal EnableDelayedExpansion

my-application && exit 0 || exit !ERRORLEVEL!

The batch file executor seems to read the file one line at the time, so always exiting on that line means it will never try to read anything more from the batch file and so it doesn't matter if the batch file has been modified.

setlocal EnabledDelayedExpansion is important as otherwise ERRORLEVEL is evaluated before the application is run and so the script always returns 0 even if the application fails.

Charles
  • 155
  • 8
  • 1
    I recommend reading [Which cmd.exe internal commands clear the ERRORLEVEL to 0 upon success?](https://stackoverflow.com/questions/34968009/) and [What are the ERRORLEVEL values set by internal cmd.exe commands?](https://stackoverflow.com/questions/34987885/) You can read that using just `exit` or `exit /B` or its equivalent `goto :EOF` does not modify current `errorlevel` which means `cmd.exe` exits with the exit code of `my-application` on using just `my-application & exit` or `my-application & exit /B` or `my-application & goto :EOF`. – Mofi Jul 21 '19 at 14:26