Created
May 27, 2023 21:32
-
-
Save darianmiller/4df2423d57a83c903a3a410ce1e978bd to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
:: Source | |
:: Batch file example from May 2023 blog post: https://www.ideasawakened.com/post/prevent-concurrent-execution-batch-file-implementation-how-to | |
@echo off | |
:: | |
:: Note - this extra call is to avoid a bug with %~f0 when the script | |
:: is executed with quotes around the script name. | |
:: | |
:: %1 %2 %3 are example command-line parameters, include as desired | |
:: | |
call :getLock %1 %2 %3 | |
exit /b | |
:: Redirection | |
:: The Windows NT command processor interprets a single digit followed by a redirection | |
:: symbol as a request to redirect to the handle represented that single digit. | |
:: Handles 0, 1, and 2 are the standard input, standard output, and standard error, respectively. | |
:: In Powershell, 3,4,5,6 are used for warning,verbose,debug,info output, so we will use 9 as its currently undefined | |
:: | |
:: Path | |
:: %~f0 expands to the fully qualified path of this batch file | |
:: | |
:: Access | |
:: >> Opens the file in append mode and fails if already in use | |
:: | |
:getLock | |
call :singleuser-main %1 %2 %3 9>>"%~f0" | |
exit /b | |
:singleuser-main | |
:: Body of your script goes here. Only one process can ever get here at a time. | |
:: The lock on this batch file will be released upon return from this routine, | |
:: or when the script terminates for any reason | |
echo %* | |
pause |
Uh I never noticed those empty spaces in such scenarios. But then again it has been quite a while since I used batch files lat time for anything more than just some quick testing.
The caret feature was added in Windows NT back in 1993 so it's definitely an old, crufty feature that probably few people know about.
Well that was before I even started programming. And while my first "codding" attempts were actually with batch files I must admit that I haven't known about caret feature till today.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks, I hope it's helpful. It recently came in handy for me so I blogged about it.
Using your approach means it is no longer a single digit before the redirection operator, it's a space character right before the redirection operator, so the rule still applies. 😎
And, if you execute
echo 1 >test.txt
you will end up with a 1 followed by a singular space in that output file.