I have a batch file that computes a variable via a series of intermediate variables:
#echo off
setlocal
set base=compute directory
set pkg=compute sub-directory
set scripts=%base%\%pkg%\Scripts
endlocal
%scripts%\activate.bat
The script on the last line isn't called, because it comes after endlocal, which clobbers the scripts environment variable, but it has to come after endlocal because its purpose is to set a bunch of other environment variables for use by the user.
How do I call a script who's purpose is to set permanent environment variables, but who's location is determined by a temporary environment variable?
I know I can create a temporary batch file before endlocal and call it after endlocal, which I will do if nothing else comes to light, but I would like to know if there is a less cringe-worthy solution.
The ENDLOCAL & SET VAR=%TEMPVAR% pattern is classic. But there are situations where it is not ideal.
If you do not know the contents of TEMPVAR, then you might run into problems if the value contains special characters like < > & or|. You can generally protect against that by using quotes like SET "VAR=%TEMPVAR%", but that can cause problems if there are special characters and the value is already quoted.
A FOR expression is an excellent choice to transport a value across the ENDLOCAL barrier if you are concerned about special characters. Delayed expansion should be enabled before the ENDLOCAL, and disabled after the ENDLOCAL.
setlocal enableDelayedExpansion
set "TEMPVAR=This & "that ^& the other thing"
for /f "delims=" %%A in (""!TEMPVAR!"") do endlocal & set "VAR=%%~A"
Limitations:
If delayed expansion is enabled after the ENDLOCAL, then the final value will be corrupted if the TEMPVAR contained !.
values containing a lineFeed character cannot be transported
If you must return multiple values, and you know of a character that cannot appear in either value, then simply use the appropriate FOR /F options. For example, if I know that the values cannot contain |:
setlocal enableDelayedExpansion
set "temp1=val1"
set "temp2=val2"
for /f "tokens=1,2 delims=|" %%A in (""!temp1!"|"!temp2!"") do (
endLocal
set "var1=%%~A"
set "var2=%%~B"
)
If you must return multiple values, and the character set is unrestricted, then use nested FOR /F loops:
setlocal enableDelayedExpansion
set "temp1=val1"
set "temp2=val2"
for /f "delims=" %%A in (""!temp1!"") do (
for /f "delims=" %%B in (""!temp2!"") do (
endlocal
set "var1=%%~A"
set "var2=%%~B"
)
)
Definitely check out jeb's answer for a safe, bullet proof technique that works for all possible values in all situations.
2017-08-21 - New function RETURN.BAT
I've worked with DosTips user jeb to develop a batch utility called RETURN.BAT that can be used to exit from a script or called routine and return one or more variables across the ENDLOCAL barrier. Very cool :-)
Below is version 3.0 of the code. I most likely will not keep this code up-to-date. Best to follow the link to make sure you get the latest version, and to see some example usage.
RETURN.BAT
::RETURN.BAT Version 3.0
#if "%~2" equ "" (goto :return.special) else goto :return
:::
:::call RETURN ValueVar ReturnVar [ErrorCode]
::: Used by batch functions to EXIT /B and safely return any value across the
::: ENDLOCAL barrier.
::: ValueVar = The name of the local variable containing the return value.
::: ReturnVar = The name of the variable to receive the return value.
::: ErrorCode = The returned ERRORLEVEL, defaults to 0 if not specified.
:::
:::call RETURN "ValueVar1 ValueVar2 ..." "ReturnVar1 ReturnVar2 ..." [ErrorCode]
::: Same as before, except the first and second arugments are quoted and space
::: delimited lists of variable names.
:::
::: Note that the total length of all assignments (variable names and values)
::: must be less then 3.8k bytes. No checks are performed to verify that all
::: assignments fit within the limit. Variable names must not contain space,
::: tab, comma, semicolon, caret, asterisk, question mark, or exclamation point.
:::
:::call RETURN init
::: Defines return.LF and return.CR variables. Not required, but should be
::: called once at the top of your script to improve performance of RETURN.
:::
:::return /?
::: Displays this help
:::
:::return /V
::: Displays the version of RETURN.BAT
:::
:::
:::RETURN.BAT was written by Dave Benham and DosTips user jeb, and was originally
:::posted within the folloing DosTips thread:
::: http://www.dostips.com/forum/viewtopic.php?f=3&t=6496
:::
::==============================================================================
:: If the code below is copied within a script, then the :return.special code
:: can be removed, and your script can use the following calls:
::
:: call :return ValueVar ReturnVar [ErrorCode]
::
:: call :return.init
::
:return ValueVar ReturnVar [ErrorCode]
:: Safely returns any value(s) across the ENDLOCAL barrier. Default ErrorCode is 0
setlocal enableDelayedExpansion
if not defined return.LF call :return.init
if not defined return.CR call :return.init
set "return.normalCmd="
set "return.delayedCmd="
set "return.vars=%~2"
for %%a in (%~1) do for /f "tokens=1*" %%b in ("!return.vars!") do (
set "return.normal=!%%a!"
if defined return.normal (
set "return.normal=!return.normal:%%=%%3!"
set "return.normal=!return.normal:"=%%4!"
for %%C in ("!return.LF!") do set "return.normal=!return.normal:%%~C=%%~1!"
for %%C in ("!return.CR!") do set "return.normal=!return.normal:%%~C=%%2!"
set "return.delayed=!return.normal:^=^^^^!"
) else set "return.delayed="
if defined return.delayed call :return.setDelayed
set "return.normalCmd=!return.normalCmd!&set "%%b=!return.normal!"^!"
set "return.delayedCmd=!return.delayedCmd!&set "%%b=!return.delayed!"^!"
set "return.vars=%%c"
)
set "err=%~3"
if not defined err set "err=0"
for %%1 in ("!return.LF!") do for /f "tokens=1-3" %%2 in (^"!return.CR! %% "") do (
(goto) 2>nul
(goto) 2>nul
if "^!^" equ "^!" (%return.delayedCmd:~1%) else %return.normalCmd:~1%
if %err% equ 0 (call ) else if %err% equ 1 (call) else cmd /c exit %err%
)
:return.setDelayed
set "return.delayed=%return.delayed:!=^^^!%" !
exit /b
:return.special
#if /i "%~1" equ "init" goto return.init
#if "%~1" equ "/?" (
for /f "tokens=* delims=:" %%A in ('findstr "^:::" "%~f0"') do #echo(%%A
exit /b 0
)
#if /i "%~1" equ "/V" (
for /f "tokens=* delims=:" %%A in ('findstr /rc:"^::RETURN.BAT Version" "%~f0"') do #echo %%A
exit /b 0
)
#>&2 echo ERROR: Invalid call to RETURN.BAT
#exit /b 1
:return.init - Initializes the return.LF and return.CR variables
set ^"return.LF=^
^" The empty line above is critical - DO NOT REMOVE
for /f %%C in ('copy /z "%~f0" nul') do set "return.CR=%%C"
exit /b 0
#ECHO OFF
SETLOCAL
REM Keep in mind that BAR in the next statement could be anything, including %1, etc.
SET FOO=BAR
ENDLOCAL && SET FOO=%FOO%
The answer of dbenham is a good solution for "normal" strings, but it fails with exclamation marks ! if delayed expansion is enabled after ENDLOCAL (dbenham said this too).
But it will always fail with some tricky contents like embedded linefeeds,
as the FOR/F will split the content into multiple lines.
This will result into strange behaviour, the endlocal will executed multiple times (for each line feed), so the code isn't bullet proof.
There exists bullet proof solutions, but they are a bit messy :-)
A macro version exists SO:Preserving exclamation ..., to use it is easy, but to read it is ...
Or you could use a code block, you can paste it into your functions.
Dbenham and I developed this technic in the thread Re: new functions: :chr, :asc, :asciiMap,
there are also the explanations for this technic
#echo off
setlocal EnableDelayedExpansion
cls
for /f %%a in ('copy /Z "%~dpf0" nul') do set "CR=%%a"
set LF=^
rem TWO Empty lines are neccessary
set "original=zero*? %%~A%%~B%%~C%%~L!LF!one&line!LF!two with exclam^! !LF!three with "quotes^&"&"!LF!four with ^^^^ ^| ^< ^> ( ) ^& ^^^! ^"!LF!xxxxxwith CR!CR!five !LF!six with ^"^"Q ^"^"L still six "
setlocal DisableDelayedExpansion
call :lfTest result original
setlocal EnableDelayedExpansion
echo The result with disabled delayed expansion is:
if !original! == !result! (echo OK) ELSE echo !result!
call :lfTest result original
echo The result with enabled delayed expansion is:
if !original! == !result! (echo OK) ELSE echo !result!
echo ------------------
echo !original!
goto :eof
::::::::::::::::::::
:lfTest
setlocal
set "NotDelayedFlag=!"
echo(
if defined NotDelayedFlag (echo lfTest was called with Delayed Expansion DISABLED) else echo lfTest was called with Delayed Expansion ENABLED
setlocal EnableDelayedExpansion
set "var=!%~2!"
rem echo the input is:
rem echo !var!
echo(
rem ** Prepare for return
set "var=!var:%%=%%~1!"
set "var=!var:"=%%~2!"
for %%a in ("!LF!") do set "var=!var:%%~a=%%~L!"
for %%a in ("!CR!") do set "var=!var:%%~a=%%~3!"
rem ** It is neccessary to use two IF's else the %var% expansion doesn't work as expected
if not defined NotDelayedFlag set "var=!var:^=^^^^!"
if not defined NotDelayedFlag set "var=%var:!=^^^!%" !
set "replace=%% """ !CR!!CR!"
for %%L in ("!LF!") do (
for /F "tokens=1,2,3" %%1 in ("!replace!") DO (
ENDLOCAL
ENDLOCAL
set "%~1=%var%" !
#echo off
goto :eof
)
)
exit /b
I want to contribute to this too and tell you how you can pass over an array-like set of variables:
#echo off
rem clean up array in current environment:
set "ARRAY[0]=" & set "ARRAY[1]=" & set "ARRAY[2]=" & set "ARRAY[3]="
rem begin environment localisation block here:
setlocal EnableExtensions
rem define an array:
set "ARRAY[0]=1" & set "ARRAY[1]=2" & set "ARRAY[2]=4" & set "ARRAY[3]=8"
rem `set ARRAY` returns all variables starting with `ARRAY`:
for /F "tokens=1,* delims==" %%V in ('set ARRAY') do (
if defined %%V (
rem end environment localisation block once only:
endlocal
)
rem re-assign the array, `for` variables transport it:
set "%%V=%%W"
)
rem this is just for prove:
for /L %%I in (0,1,3) do (
call echo %%ARRAY[%%I]%%
)
exit /B
The code works, because the very first array element is queried by if defined within the setlocal block where it is actually defined, so endlocal is executed once only. For all the successive loop iterations, the setlocal block is already ended and therefore if defined evaluates to FALSE.
This relies on the fact that at least one array element is assigned, or actually, that there is at least one variable defined whose name starts with ARRAY, within the setlocal/endlocal block. If none exist therein, endlocal is not going to be executed. Outside of the setlocal block, no such variable must be defined, because otherwise, if defined evaluates to TRUE more than once and therefore, endlocal is executed multiple times.
To overcome this restrictions, you can use a flag-like variable, according to this:
clear the flag variable, say ARR_FLAG, before the setlocal command: set "ARR_FLAG=";
define the flag variable inside of the setlocal/endlocal block, that is, assign a non-empty value to it (immediately before the for /F loop preferrably): set "ARR_FLAG=###";
change the if defined command line to: if defined ARR_FLAG (;
then you can also do optionally:
change the for /F option string to "delims=";
change the set command line in the for /F loop to: set "%%V";
Something like the following (I haven't tested it):
#echo off
setlocal
set base=compute directory
set pkg=compute sub-directory
set scripts=%base%\%pkg%\Scripts
pushd %scripts%
endlocal
call .\activate.bat
popd
Since the above doesn't work (see Marcelo's comment), I would probably do this as follows:
set uniquePrefix_base=compute directory
set uniquePrefix_pkg=compute sub-directory
set uniquePrefix_scripts=%uniquePrefix_base%\%uniquePrefix_pkg%\Scripts
set uniquePrefix_base=
set uniquePrefix_pkg=
call %uniquePrefix_scripts%\activate.bat
set uniquePrefix_scripts=
where uniquePrefix_ is chosen to be "almost certainly" unique in your environment.
You could also test on entry to the bat file that the "uniquePrefix_..." environment variables are undefined on entry as expected - if not you can exit with an error.
I don't like copying the BAT to the TEMP directory as a general solution because of (a) the potential for a race condition with >1 caller, and (b) in the general case a BAT file might be accessing other files using a path relative to its location (e.g. %~dp0..\somedir\somefile.dat).
The following ugly solution will solve (b):
setlocal
set scripts=...whatever...
echo %scripts%>"%TEMP%\%~n0.dat"
endlocal
for /f "tokens=*" %%i in ('type "%TEMP%\%~n0.dat"') do call %%i\activate.bat
del "%TEMP%\%~n0.dat"
For surviving multiple variables: If you choose to go with the "classic"
ENDLOCAL & SET VAR=%TEMPVAR% mentioned sometimes in other responses here (and are satisfied that the drawbacks shown in some of the responses are addressed or are not an issue), note that you can do multiple variables, a la ENDLOCAL & SET var1=%local1% & SET var2=%local2%.
I share this because other than the linked site below, I have only seen the "trick" illustrated with a single variable, and like myself some may have incorrectly assumed that it only "works" for a single variable.
Docs: https://ss64.com/nt/endlocal.html
To answer my own question (in case no other answer comes to light, and to avoid repeats of the one I already know about)...
Create a temporary batch file before calling endlocal that contains the command to call the target batch file, then call and delete it after endlocal:
echo %scripts%\activate.bat > %TEMP%\activate.bat
endlocal
call %TEMP%\activate.bat
del %TEMP%\activate.bat
This is so ugly, I want to hang my head in shame. Better answers are most welcome.
How about this.
#echo off
setlocal
set base=compute directory
set pkg=compute sub-directory
set scripts=%base%\%pkg%\Scripts
(
endlocal
"%scripts%\activate.bat"
)
Related
The file is not added in the destination path if it has spaces in the file name.
For example, if the filename is textfile1.txt -> it will be added in the destination path. However, if the directory filename has space like this text file4.txt it will not be added.
Is there a way to remove the spaces of the filename?
Here is the image:
Here is my main concern:
Here is my script:
#ECHO off
TITLE (c) ASDG
SETLOCAL EnableDelayedExpansion
SET locationPath=C:\Textfiles\
SET destinationPath=E:\Textfiles\
SET status=success
SET countMetadata=0
SET countPDF=0
SET countJPEG=0
ECHO Executing the program...
FOR /R %locationPath% %%g IN (*.txt) DO (
CD %%~dpg
IF EXIST *.txt* (
FOR /F "skip=1 tokens=1* delims=|" %%a IN (%%~nxg) DO (
SET /a countMetadata+=1
ECHO %%~dpa%%a^| %%b >> %destinationPath%^%%~nxg
)
IF %status% == success (
ECHO %%g has been successfully added
ECHO %%g >> %destinationPath%^logs.txt
)
)
)
After reformatting to use indentation to show code blocks (parenthesised code that is parsed, substituting %variables%, then executed), I then applied various recommendations:
Use set "var=value" for setting string values - this avoids problems caused by trailing spaces. Don't assign " or a terminal backslash or Space. Build pathnames from the elements - counterintuitively, it is likely to make the process easier. If the syntax set var="value" is used, then the quotes become part of the value assigned.
Use set /a to assign numeric values. No quotes required.
THIS CODE WILL NOT FULLY PERFORM THE REQUIRED TASK
Without comments to explain why some code is used, it's difficult to provide guidance.
#ECHO OFF
SETLOCAL EnableDelayedExpansion
TITLE (c) ASDG
SET "locationPath=C:\Textfiles"
SET "destinationPath=E:\Textfiles"
SET "status=success"
SET /a countMetadata=0
SET /a countPDF=0
SET /a countJPEG=0
ECHO Executing the program...
FOR /R "%locationPath%" %%g IN (*.txt) DO (
CD %%~dpg
IF EXIST *.txt* (
FOR /F "usebackq skip=1 tokens=1* delims=|" %%a IN ("%%~nxg") DO (
SET /a countMetadata+=1
ECHO %%~dpa%%a^| %%b >> %destinationPath%\%%~nxg
)
IF !status! == success (
ECHO %%g has been successfully added
ECHO %%g >> %destinationPath%\logs.txt
)
)
)
GOTO :EOF
Modifications explanation
I prefer the setlocal to be the second line. YMMV.
Set commands modified as explained above
locationpath in the for /R quoted - it may contain separators like spaces.
%%~nxg quoted in for...%%a as it may contain spaces
usebackq added to for...%%a as %%~nxg is now quoted
I prefer to avoid ADFNPSTXZ (in either case) as metavariables (loop-control variables)
ADFNPSTXZ are also metavariable-modifiers which can lead to difficult-to-find bugs
(See `for/f` from the prompt for documentation)
Not sure what is going on with the following echo, but destinationPath no longer has the terminal \. Same comment applies to the following ECHO %%g.
!staus! replaces %status% (logically) as logically, status may change within the block - the delayed expansion trap
BUT status is not being varied within the block, so its value will always be its initial value, success.
Using Boolean
So - a few things for OP to clean up...
I need to escape "!" (and other special chars) in a for-loop where delayed variable expansion is enabled
I've tried manually escaping the loop-varible with string substitution ^^! in the loop-variable, %%a but with no luck at all. Is it already too late after the for has read them? If so, how the heck can I even accomplish this?
Below is a short function. The only relevant part here is the for-loop and the echo statement. That is printing out whole lines from a file every X'th line, and those lines are file-paths. They (sometimes) contain characters like "!" and other troublesome special characters. I just want echo here to pass it without interpreting it at all - but instead it ends up deleting my "!" chars.
For my use they need to be exactly correct or they are useless as they must correlate to actual files later on in what I use them for.
setlocal EnableDelayedExpansion
:SplitList
if [%3] == [] goto :SplitListUsage
set inputfile=%~1
set outputfile=%~2
set splitnumber=%~3
set skipLines=0
set skipLines=%~4
if %skipLines% GTR 0 (
set skip=skip=%skipLines%
) else (
set skip=
)
#echo off > %outputfile%
set lineNumber=0
for /f "tokens=* %skip% delims= " %%a in (%inputfile%) do (
set /a modulo="!lineNumber! %% !splitnumber!"
if "!modulo!" equ "0" (
echo %%a >> !outputfile!
)
set /a lineNumber+=1
)
exit /B 0
Quick solution:
if !modulo! equ 0 (
setlocal DisableDelayedExpansion
(echo %%a)>> "%outputfile%"
endlocal
)
Better solution:
Based on your code sample, there is no need to have delayed expansion enabled for the entire code,in fact you should keep it disabled to not mess with the file names or input strings which may contain !, and enabled it when necessary:
setlocal DisableDelayedExpansion
REM Rest of the code...
for /f "tokens=* %skip% delims= " %%a in (%inputfile%) do (
set /a "modulo=lineNumber %% splitnumber"
setlocal EnableDelayedExpansion
for %%m in (!modulo!) do (
endlocal
REM %%m is now have the value of modulo
if %%m equ 0 (
(echo %%a)>> "%outputfile%"
)
)
set /a lineNumber+=1
)
Side notes:
There are some other issues with your code which as you might have noticed, some of them are corrected in the above solutions. But to not distract you from main issue you had, I covered them here separately.
There is also room for improving the performance of the code when writing to the outputfile.
Here is the re-written code which covers the rest:
#echo off
setlocal DisableDelayedExpansion
:SplitList
if "%~3"=="" goto :SplitListUsage
set "inputfile=%~1"
set "outputfile=%~2"
set "splitnumber=%~3"
set "skipLines=0"
set /a "skipLines=%~4 + 0" 2>nul
if %skipLines% GTR 0 (
set "skip=skip=%skipLines%"
) else (
set "skip="
)
set "lineNumber=0"
(
for /f "usebackq tokens=* %skip% delims= " %%a in ("%inputfile%") do (
set /a "modulo=lineNumber %% splitnumber"
setlocal EnableDelayedExpansion
for %%m in (!modulo!) do (
endlocal
REM %%m is now have the value of modulo
if %%m equ 0 echo(%%a
)
set /a lineNumber+=1
)
)>"%outputfile%"
You didn't protect the variable assignments with double qoutes " e.g. set inputfile=%~1. If the now naked batch parameter %~1 contains spaces or special characters like & your batch files fails, either fatally with a syntax error or at execution time with incorrect data. The recommended syntax is to use set "var=value" which does not assign the quotes to the variable value but provides protection against special characters. It also protects the assignment against the accidental trailing spaces.
The %inputfile% may contain special characters or spaces, so it should be protected by double quoting it when using in the FOR /F's IN clause. When double quoting the file name in FOR /F the usebackq parameter must also be used.
With SET /A there is no need to expand the variable values: set /a modulo="!lineNumber! %% !splitnumber!". The variable names can be used directly, and it will work correctly with or without delayed expansion.
Using (echo %%a) >> "%outputfile%" inside a FOR loop introduces a severe performance penalty specially with a large number of iterations, because at each iteration the output file will be opened, written to and then closed. To improve the performance The whole FOR loop can redirected once. Any new data will be appended to the already opened file.
The odd looking echo( is to protect against the empty variable values, or when the variable value is /?. Using echo %%a may print the `ECHO is on/off' message if the variable is empty or may print the echo usage help.
In the main solutions, The reason I've used (echo %%a)>> "%outputfile%" instead of echo %%a >> "%outputfile%" is to prevent outputting the extra space between %%a and >>. Now you know the reason for using echo(, it is easy to understand the safer alternative: (echo(%%a)>> "%outputfile%"
I use a portable application that have updates quite often. The problem is that each version of the application has a folder named "processing-x.y.z". Each time I install a new version, I need to associate the files with the new version which is in a different folder. So to workaround this annoyance, I want to associate the "*.pde" file type to a batch file.
The folder names go as follow
processing-3.2.1
processing-3.2.2
etc.
I have created this small batch script that get the executable from the latest version.
#echo off
for /f "delims=" %%D in ('dir processing* /a:d /b /o-n') do (
set currentFolder=%%~fD
:: Check if environment variable already set
if not %currentFolder%==%processing% (
:: Set environment variable processing
setx processing %currentFolder%
)
%currentFolder%/processing.exe %1
goto :eof
)
It works when launching it from the command-line, but not within Windows. Is there a specific reason? Also, is there a way to optimize this code?
Thanks
Supposing the version numbers always consist of a single digit each, I would do it the following way:
#echo off
rem // Reset variable:
set "currentFolder="
rem /* Loop through the folders in ascending order, overwrite the variable
rem in each iteration, so it holds the highest version finally: */
for /f "delims=" %%D in ('dir /B /A:D /O:N "processing-*.*.*"') do (
set "currentFolder=%%~fD"
)
rem // Check if environment variable is already set:
if not "%processing%"=="%currentFolder%" (
rem // Set environment variable `processing`:
setx processing "%currentFolder%"
)
rem // Execute `processing.exe`:
"%currentFolder%/processing.exe" "%~1"
If the individual version numbers can consist of more than one digit (four at most here), use this:
#echo off
setlocal EnableExtensions EnableDelayedExpansion
rem /* Assign each found folder to a variable called `$ARRAY_X_Y_Z`, where `X`, `Y`, `Z`
rem are zero-padded variants of the original numbers `x`, `y`, `z`, so for instance,
rem a folder called `processing-4.7.12` is stored in variable `$ARRAY_0004_0007_0012`: */
for /F "tokens=1-4 delims=-. eol=." %%A in ('
dir /B /A:D "processing-*.*.*" ^| ^
findstr /R /I "^processing-[0-9][0-9]*.[0-9][0-9]*.[0-9][0-9]*$"
') do (
rem // Perform the left-side zero-padding here:
set "MAJ=0000%%B" & set "MIN=0000%%C" & set "REV=0000%%D"
set "$ARRAY_!MAJ:~-4!_!MIN:~-4!_!REV:~-4!=%%A-%%B.%%C.%%D"
)
rem // Reset variable:
set "currentFolder="
rem /* Loop through the output of `set "$ARRAY_"`, which returns all variables beginning
rem with `$ARRAY_` in ascending alphabetic order; because of the zero-padding, where
rem alphabetic and alpha-numeric orders become equivalent, the item with the greatest
rem version number item is iterated lastly, therefore the latest version is returned: */
for /F "tokens=1,* delims==" %%E in ('set "$ARRAY_"') do (
set "currentFolder=%%F"
)
endlocal & set "currentFolder=%currentFolder%"
rem // The rest of the script os the same as above...
You can also find similar approaches here:
How to get latest version number using batch (this approach also relies on the sorting featurre of the set command)
How to sort lines of a text file containing version numbers in format major.minor.build.revision numerical? (this uses the sort command upon a temporary file or on piped (|) data)
not tested (edited: should handle the cases when minor versions have more digits):
#echo off
setlocal enableDelayedExpansion
set /a latest_n1=0
set /a latest_n2=0
set /a latest_n3=0
for /f "tokens=2,3* delims=-." %%a in ('dir processing* /a:d /b /o-n') do (
set "current_v=%%a.%%b.%%c"
set /a "current_n1=%%a"
set /a "current_n2=%%b"
set /a "current_n3=%%c"
if !current_n1! GTR !latest_n1! (
set /a latest_n1=!current_n1!
set /a latest_n2=!current_n2!
set /a latest_n3=!current_n3!
set "latest_v=!current_v!"
) else if !current_n1! EQU !latest_n1! if !current_n2! GTR !latest_n2! (
set /a latest_n1=!current_n1!
set /a latest_n2=!current_n2!
set /a latest_n3=!current_n3!
set "latest_v=!current_v!"
) else if !current_n1! EQU !latest_n1! if !current_n2! EQU !latest_n2! if !current_n3! GTR !latest_n3! (
set /a latest_n1=!current_n1!
set /a latest_n2=!current_n2!
set /a latest_n3=!current_n3!
set "latest_v=!current_v!"
)
)
echo latest version=processing-%latest_v%
#echo off
for /f "delims=" %%D in ('dir processing* /a:d /b /o-n') do (
if "%processing%" neq "%cd%\%%F" setx processing "%cd%\%%F" >nul
.\%%F\processing.exe %1
goto :eof
)
is equivalent code - almost.
First problem - the :: form of comments should not be used within a code block (parenthesised series of statements) as :: is in fact a label that itself stars with a colon. Since it is a label, it terminates the block.
Next problem - within a code block, %var% refers to the value ofvar**as it stood when thefor` was encountered** - not as it changes within the loop.
Next problem - as noted by others, /o-n produces a by-name sequence, so 10 is likely to sort after 9 (since the sort is reversed). I've not changed this in the replacement code, but /o-d to sort by reverse-date may be better suited to your application.
Now to how your code works.
First, processing is set to whatever the last run established. If that is different from the value calculated from this run, then setx the new value. Bizarrely, setx does not set the value in the current cmd instance, only for instances created in the future.
You then attempt to execute your process and then exit the batch with the goto :eof. Only problem is that %currentfolder% is not the value as changed by the loop, because it's supposed to be in the code block. It appears to change because the ::-comments have broken the block and where currentfolder is used in your code, it is outside of the block.
Instead, use .\%%F\executablename which means "from the current directoryname (.);subdirectory %%F;filenametoexecute" - note that "\" is a directory-separator in windows, '/' indicates a switch.
Hi I am trying to write a script that updates the MAJOR and MINOR version numbers in a header/text file, I am trying to use the "FOR /F " command but out of ideas.
Below is the Header file to which I need to update the values corresponding to "MAJOR_VERSION" and "MINOR_VERSION "
#ifndef _VERSION_H_
#define _VERSION_H_
//---------- Lock Firmware Package Version ------------
//Lock firmware package
#define MAJOR_VERSION 3 //0-255
#define MINOR_VERSION 58 //0-255
#define REVISION_VERSION 0 //0-255 should generally always be 0 unless the meaning change
//---------- VERSION ----------------------
The following script -- let us call it update-versions.bat -- should do what you want:
#echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Parse command line arguments:
set "DIRN=#define"
set "FILE=%~1"
if not defined FILE (>&2 echo ERROR: too few arguments!) & exit /B 1
shift /1
set /A "IDX=0"
:ARGS
set "ARGV=%~1"
if not defined ARGV goto :SKIP
set /A "IDX+=1"
set "KEY[%IDX%]=%ARGV::=" & rem "%"
if not defined KEY[%IDX%] set /A "IDX-=1" & goto :SKIP
set "VER[%IDX%]=10000%ARGV:*:=%"
set /A "VER[%IDX%]%%=10000"
shift /1
goto :ARGS
:SKIP
rem // Process file:
for /F "delims=" %%L in ('findstr /N /R "^" "%FILE%" ^& ^> "%FILE%" rem/') do (
set "LINE=%%L"
setlocal EnableDelayedExpansion
(
for /F "tokens=1-3*" %%A in ("!LINE:*:=!") do (
endlocal
if /I "%%A"=="%DIRN%" (
set "VER=" & set "ITEM=%%B" & set "REST=%%D"
setlocal EnableDelayedExpansion
for /L %%I in (1,1,%IDX%) do (
if /I "!ITEM!"=="!KEY[%%I]!" (
set "KEY=!KEY[%%I]!"
set "VER=!VER[%%I]!"
)
)
if defined VER (
>> "!FILE!" echo(!DIRN! !KEY! !VER! !REST!
) else (
>> "!FILE!" echo(!LINE:*:=!
)
) else (
setlocal EnableDelayedExpansion
>> "!FILE!" echo(!LINE:*:=!
)
)
) || (>> "!FILE!" echo/)
endlocal
)
endlocal
exit /B
To use it, you need to provide the file to modify and the version information as command line arguments:
update-versions.bat "\path\to\file.h" MAJOR_VERSION:3 MINOR_VERSION:59 REVISION_VERSION:0
As you can see the first argument is the path to the file, which is mandatory. Each of the remaining arguments specifies a version number keyword (appearing after the #defined directive) and the related new version number, separated by a colon; all these are optional arguments.
This is my answer to an identical question That was deleted by the owner "Dinesh" after I'd answered it yesterday.
#ECHO OFF
SETLOCAL
SET "sourcedir=U:\sourcedir"
SET "filename1=%sourcedir%\q40733227.txt"
SET "itemlist=major_version minor_version"
FOR /f "usebackqtokens=1-3*" %%a IN ("%filename1%") DO (
FOR %%i IN (%itemlist%) DO IF /i "%%b"=="%%i" SET "%%b=%%c"
)
FOR %%i IN (%itemlist%) DO SET %%i
GOTO :EOF
You would need to change the setting of sourcedir to suit your circumstances.
I used a file named q40733227.txt containing your data for my testing.
Tokenise each line using the defaults. The string in the second token (for the values selected by itemlist) should take on the value in the third token.
You could extend the values extracted in the obvious way, extend itemlist
Here is a simple script that uses JREPL.BAT - a regular expression find/replace utility. JREPL is pure scrpt (hybrid batch/JScript) that runs natively on any Windows machine from XP onward - no 3rd party exe file required. Full documentation is available from the command line via jrepl /?, or jrepl /?? for paged help.
updateHeader.bat
#echo off
setlocal
set "var="
:loadVar
set "%~2=%~3"
set "var=%Var%%~2|"
shift /2
shift /2
if "%~2" neq "" goto :loadVar
call jrepl "(#define +(%var:~0,-1%) +)\d+" "$txt=$1+env($2)" /jq /f %1 /o -
The batch script parses the command line arguments. It builds a list of variable names to be replaced (simple regular expression alternation), and also sets an environment variable for each specified variable. The JREPL call replaces each value with the value of the corresponding environment variable.
The syntax for using the above script is updateHeader File Variable=Value[ Variable=Value].... The Variable names are case sensitive.
For example, to update file "version.h" with major version=4 and minor version=01:
updateHeader version.h MAJOR_VERSION=4 MINOR_VERSION=01
Or you could update just the revision version to 1, and specify a different path for the file:
updateHeader "c:\somePath\version.h" REVISION_VERSION=1
You can specify as many replacements as you like, as long as each line to be replaced has the form #define VARIABLE value .... The number of spaces can vary.
I have a function that takes a variable number of arguments. Each argument is a reference that the function will modify directly. Here is how I call the function:
set "A=" && set "B=" && set "C="
call :variadic_func A B C
echo [%A%][%B%][%C%]
goto :eof
If I don't use setlocal to limit variable scope, the function works fine. The function creates references X, Y, and Z and assigns them 1, 2, and 3. When the function returns, the caller sees that its variables A, B, and C are 1, 2, and 3. Good. Pretend that this is a variadic function and it figures out how many arguments it has at runtime.
:variadic_func
set "x=%1" && set "y=%2" && set "z=%3"
set "%x%=1" && set "%y%=2" && set "%z%=3"
goto :eof
Output:
C:\scratch\variadic_batch>variadic.bat
[1][2][3]
But I want to limit the scope of my function's variables with setlocal. So that means any values I write to X, Y, and Z get thrown away at the endlocal. How do I get the values out of the function?
:variadic_func
setlocal
set "x=%1" && set "y=%2" && set "z=%3"
set "%x%=1" && set "%y%=2" && set "%z%=3"
endlocal && (
call set "%x%=%%%%x%%%%"
call set "%y%=%%%%y%%%%"
call set "%z%=%%%%z%%%%"
)
goto :eof
Unfortunately, the calling context receives the values %x%, %y%, and %z%. I thought the code above would be expanded like so: 1. Expand %x% first to get call set A=%%A%%. Then the call gets executed and it would evaluate A=%A%. But I just end up assigning the text %A% to the variable A instead of evaluating it.
C:\scratch\variadic_batch>variadic.bat
[%x%][%y%][%z%]
Why is it not working like I expect, and how do I fix it?
(I just thought of doing a setlocal EnableDelayedExpansion before the function call so maybe delayed expansion would still be available when I do the endlocal in the function, but even if that works it'd be nice if the function didn't rely on the caller to be in a delayed expansion block... and I don't even know whether delayed expansion blocks stack)
This is an interesting topic! If you know in advance how many variables the function will get, you can assemble the appropiate line at end to return the values to the caller's environment this way:
:variadic_func
setlocal EnableDelayedExpansion
set "x=%1" & set "y=%2" & set "z=%3"
set "%x%=1" & set "%y%=2" & set "%z%=3"
for /F "tokens=1-3" %%a in ("!%x%! !%y%! !%z%!") do (
endlocal
set "%x%=%%a" & set "%y%=%%b" & set "%z%=%%c"
)
exit /B
However, if the number of variables is unknow, previous method can not be used.
(I used exit /B to terminate subroutines and goto :EOF for the main file only)
Your example is imprecise anyway, because if you don't know how many variables comes, you can NOT use fixed names as "x", "y" or "z". The only way to manage this situation is storing the names in an array and then process the array elements.
This way, before the function ends we could assemble a list of "var=value" pairs that will be executed in a FOR after the endlocal, so the variables will be defined in the caller's environment:
#echo off
call :variadic_func One Two Three
echo THREE VARS: One=[%One%] Two=[%Two%] Three=[%Three%] Four=[%Four%] Five=[%Five%]
call :variadic_func One Two Three Four Five
echo FIVE VARS: One=[%One%] Two=[%Two%] Three=[%Three%] Four=[%Four%] Five=[%Five%]
goto :EOF
:variadic_func
setlocal EnableDelayedExpansion
rem Collect the list of variable names in "var" array:
set i=0
:nextVar
if "%1" equ "" goto endVars
set /A i+=1
set var[%i%]=%1
shift
goto nextVar
:endVars
rem Assign random numbers to the variables (for example):
for /L %%i in (1,1,%i%) do (
set !var[%%i]!=!random!
)
rem Assemble the list of "var=value" assignments that will be executed at end:
set assignments=
for /L %%i in (1,1,%i%) do (
for %%v in (!var[%%i]!) do (
set assignments=!assignments! "%%v=!%%v!"
)
)
rem Execute the list of variable assignments in the caller's environment:
endlocal & for %%a in (%assignments%) do set %%a
exit /B
Output:
THREE VARS: One=[29407] Two=[21271] Three=[5873] Four=[] Five=[]
FIVE VARS: One=[30415] Two=[2595] Three=[22479] Four=[13956] Five=[26412]
EDIT:
I borrowed the method from dbenham's solution to return any number of variables with no limitations, excepting those noted by him. This is the new version:
#echo off
call :variadic_func One Two Three
echo THREE VARS: One=[%One%] Two=[%Two%] Three=[%Three%] Four=[%Four%] Five=[%Five%]
call :variadic_func One Two Three Four Five
echo FIVE VARS: One=[%One%] Two=[%Two%] Three=[%Three%] Four=[%Four%] Five=[%Five%]
goto :EOF
:variadic_func
setlocal EnableDelayedExpansion
rem Assemble the list of variable names in "var" array:
set i=0
:nextVar
if "%1" equ "" goto endVars
set /A i+=1
set var[%i%]=%1
shift
goto nextVar
:endVars
rem Assign random numbers to the variables (for example):
for /L %%i in (1,1,%i%) do (
set !var[%%i]!=!random!
)
rem Complete "var[i]=name" array contents to "var[i]=name=value"
for /L %%i in (1,1,%i%) do (
for %%v in (!var[%%i]!) do (
set "var[%%i]=%%v=!%%v!"
)
)
rem Execute the list of variable assignments in the caller's environment:
for /F "tokens=1* delims==" %%a in ('set var[') do endlocal & set "%%b"
exit /B
Antonio
Very interesting question, and I'm surprised how easy it is to solve :-)
EDIT - My original answer didn't quite answer the question, as Aacini noted in his comment. At the bottom I have a version that does directly answer the question. I've also updated my original answer to include a few more limitations that I discovered
You can return any number of variables very easily if you stipulate that the names of all variables to be returned are prepended with a constant prefix. The return variable prefix can be passed in as one of your parameters.
The following line is all that is needed:
for /f "delims=" %%A in ('set prefix.') do endlocal & set "%%A"
The entire results of the set prefix command is buffered before any iterations take place. The first iteration executes the only ENDLOCAL that is required to get back to the environment state that existed prior to the CALL. The subsequent ENDLOCAL iterations do no harm because ENDLOCAL within a CALLed function only work on SETLOCALs that were issued within the CALL. Additional redundant ENDLOCAL are ignored.
There are some really nice features of this very simple solution:
There is theoretically no limit to the number of variables that are returned.
The returned values can contain almost any combination of characters.
The returned values can approach the theoretical maximum length of 8191 bytes long.
There are also a few limitations:
The returned value cannot contain line feeds
If the final character of a returned value is a carriage return, that final carriage return will be stripped.
Any returned value that contains ! will be corrupted if delayed expansion is enabled when the CALL is made.
I have not figured out an elegant method to set a returned variable to undefined.
Here is a simple example of a variadic function that returns a variable number of values
#echo off
setlocal
set varBeforeCall=ok
echo(
call :variadic callA 10 -34 26
set callA
set varBeforeCall
echo(
call :variadic callB 1 2 5 10 50 100
set callB
set varBeforeCall
exit /b
:variadic returnPrefix arg1 [arg2 ...]
#echo off
setlocal enableDelayedExpansion
set /a const=!random!%%100
:: Clear any existing returnPrefix variables
for /f "delims==" %%A in ('set %1. 2^>nul') do set "%%A="
:: Define the variables to be returned
set "%~1.cnt=0"
:argLoop
if "%~2" neq "" (
set /a "%~1.cnt+=1"
set /a "%~1.!%~1.cnt!=%2*const"
shift /2
goto :argLoop
)
:: Return the variables accross the ENDLOCAL barrier
for /f "delims=" %%A in ('set %1. 2^>nul') do endlocal & set "%%A"
exit /b
And here is a sample run result:
callA.1=40
callA.2=-136
callA.3=104
callA.cnt=3
varBeforeCall=ok
callB.1=24
callB.2=48
callB.3=120
callB.4=240
callB.5=1200
callB.6=2400
callB.cnt=6
varBeforeCall=ok
Here is a version that is safe to CALL when delayed expansion is enabled
With a bit of extra code, it is possible to remove the limitation regarding CALLing the function while delayed expansion is enabled and the return value contains !.
The returned values are manipulated as necessary to protect ! when delayed expansion is enabled. The code is optimized such that the relatively expensive minipulation (particularly the CALL) is only executed when delayed expansion was enabled and the value contains !.
The returned value still cannot contain line feeds. A new limitation is that all carriage returns will be stripped if the returned value contains ! and delayed expansion was enabled when the CALL was made.
Here is a demo.
#echo off
setlocal
set varBeforeCall=ok
echo(
echo Results when delayed expansion is Disabled
call :variadic callA 10 -34 26
set callA
set varBeforeCall
setlocal enableDelayedExpansion
echo(
echo Results when delayed expansion is Enabled
call :variadic callB 1 2 5 10 50 100
set callB
set varBeforeCall
exit /b
:variadic returnPrefix arg1 [arg2 ...]
#echo off
:: Determine if caller has delayed expansion enabled
setlocal
set "NotDelayed=!"
setlocal enableDelayedExpansion
set /a const=!random!%%100
:: Clear any existing returnPrefix variables
for /f "delims==" %%A in ('set %1. 2^>nul') do set "%%A="
:: Define the variables to be returned
set "%~1.cnt=0"
:argLoop
if "%~2" neq "" (
set /a "%~1.cnt+=1"
set /a "%~1.!%~1.cnt!=%2*const"
shift /2
goto :argLoop
)
set %~1.trouble1="!const!\^^&^!%%"\^^^^^&^^!%%
set %~1.trouble2="!const!\^^&%%"\^^^^^&%%
:: Prepare variables for return when caller has delayed expansion enabled
if not defined NotDelayed for /f "delims==" %%A in ('set %1. 2^>nul') do (
for /f delims^=^ eol^= %%V in ("!%%A!") do if "%%V" neq "!%%A!" (
set "%%A=!%%A:\=\s!"
set "%%A=!%%A:%%=\p!"
set "%%A=!%%A:"=\q!"
set "%%A=!%%A:^=\c!"
call set "%%A=%%%%A:^!=^^^!%%" ^^!
set "%%A=!%%A:^^=^!"
set "%%A=!%%A:\c=^^!"
set "%%A=!%%A:\q="!"
set "%%A=!%%A:\p=%%!"
set "%%A=!%%A:\s=\!"
)
)
:: Return the variables accross the ENDLOCAL barrier
for /f "delims=" %%A in ('set %1. 2^>nul') do endlocal & endlocal & set "%%A"
exit /b
And some sample results:
Results when delayed expansion is Disabled
Environment variable callA not defined
callA.1=780
callA.2=-2652
callA.3=2028
callA.cnt=3
callA.trouble1="78\^&!%"\^&!%
callA.trouble2="78\^&%"\^&%
varBeforeCall=ok
Results when delayed expansion is Enabled
Environment variable callB not defined
callB.1=48
callB.2=96
callB.3=240
callB.4=480
callB.5=2400
callB.6=4800
callB.cnt=6
callB.trouble1="48\^&!%"\^&!%
callB.trouble2="48\^&%"\^&%
varBeforeCall=ok
Note how the format of the returned trouble values is consistent whether or not delayed expansion was enabled when the CALL was made. The trouble1 value would have been corrupted when delayed expansion was enabled if it were not for the extra code because of the !.
EDIT: Here is a version that directly answers the question
The original question stipulated that the names of each returned variable are supposed to be provided in the parameter list. I modified my algorithm to prefix each variable name with a dot within the function. Then I slightly modified the final returning FOR statement to strip off the leading dot. There is a restriction that the names of the returned variables cannot begin with a dot.
This version includes the safe return technique that allows CALLs while delayed expansion is enabled.
#echo off
setlocal disableDelayedExpansion
echo(
set $A=before
set $varBeforeCall=ok
echo ($) Values before CALL:
set $
echo(
echo ($) Values after CALL when delayed expansion is Disabled:
call :variadic $A $B
set $
setlocal enableDelayedExpansion
echo(
set #A=before
set #varBeforeCall=ok
echo (#) Values before CALL:
set #
echo(
echo (#) Values after CALL when delayed expansion is Enabled:
call :variadic #A #B #C
set #
exit /b
:variadic arg1 [arg2 ...]
#echo off
:: Determine if caller has delayed expansion enabled
setlocal
set "NotDelayed=!"
setlocal enableDelayedExpansion
:: Clear any existing . variables
for /f "delims==" %%A in ('set . 2^>nul') do set "%%A="
:: Define the variables to be returned
:argLoop
if "%~1" neq "" (
set /a num=!random!%%10
set ^".%~1="!num!\^^&^!%%"\^^^^^&^^!%%"
shift /1
goto :argLoop
)
:: Prepare variables for return when caller has delayed expansion enabled
if not defined NotDelayed for /f "delims==" %%A in ('set . 2^>nul') do (
for /f delims^=^ eol^= %%V in ("!%%A!") do if "%%V" neq "!%%A!" (
set "%%A=!%%A:\=\s!"
set "%%A=!%%A:%%=\p!"
set "%%A=!%%A:"=\q!"
set "%%A=!%%A:^=\c!"
call set "%%A=%%%%A:^!=^^^!%%" ^^!
set "%%A=!%%A:^^=^!"
set "%%A=!%%A:\c=^^!"
set "%%A=!%%A:\q="!"
set "%%A=!%%A:\p=%%!"
set "%%A=!%%A:\s=\!"
)
)
:: Return the variables accross the ENDLOCAL barrier
for /f "tokens=* delims=." %%A in ('set . 2^>nul') do endlocal & endlocal & set "%%A"
exit /b
And sample results:
($) Values before CALL:
$A=before
$varBeforeCall=ok
($) Values after CALL when delayed expansion is Disabled:
$A="5\^&!%"\^&!%
$B="5\^&!%"\^&!%
$varBeforeCall=ok
(#) Values before CALL:
#A=before
#varBeforeCall=ok
(#) Values after CALL when delayed expansion is Enabled:
#A="7\^&!%"\^&!%
#B="2\^&!%"\^&!%
#C="0\^&!%"\^&!%
#varBeforeCall=ok
Remove a pair of the percents from the value. call set "%x%=%%%%x%%%%" into call set "%x%=%%%x%%%"
Currently it is evaluating as follows:
:: Here is the base command
call set "%x%=%%%%x%%%%"
:: The single percents are evaluated and the doubles are escaped.
set "A=%%x%%"
:: The doubles are escaped again leaving literal % signs
"A=%x%"
You want as follows:
:: Here is the base command
call set "%x%=%%%x%%%"
:: The single percents are evaluated and the doubles are escaped.
set "A=%A%"
:: The single percents are evaluated.
"A=1"
When doing variable expansion using the call command, single percents % get evaluate first, then double percents %% seconds due to batch escaping.
Batch commands are read from left to right. So when there are an even number of % signs such as %%%%, the first and third percent signs will be utilized as escape characters for the second and fourth leaving no percent signs left to be used for variable evaluation.