I have two batch file here, test.bat and len.bat.
len.bat is a function that receives input from test.bat, processes it and then return a result value back to test.bat.
test.bat
#echo off
setlocal EnableDelayedExpansion
call len tesla
echo !result!
pause
len.bat
#echo off
setlocal EnableDelayedExpansion
set "string=%~1"
for /l %%a in (0,1,10000) do if "!string:~%%a,1!" == "" (
set result=%%a
exit /b
)
When I open test.bat, I expect it would print a value. Instead, it says Echo is OFF.
There seem to be a problem passing the variable from len.bat to test.bat.
setlocal can be thought of as a sandbox, and anything created inside of that sandbox exists for as long as the sandbox exists. The sandbox stops existing when endlocal is called - either explicitly, or implicitly when the script ends.
In len.bat, you add a sandbox inside of the sandbox with a second setlocal enabledelayedexpansion command, and !result! is created inside of that inner sandbox. When len.bat ends, !result! is destroyed since it didn't exist before len.bat was called.
I suspect that you added the second setlocal enabledelayedexpansion because you thought it was needed to use delayed expansion inside of len.bat, but delayed expansion is actually still enabled because it was turned on in test.bat.
Delete the setlocal enabledelayedexpansion from len.bat and test.bat will correctly return "5".
If you feel that you need to keep the setlocal enabledelayedexpansion in len.bat to use it separately from test.bat, you can explicitly call endlocal and chain the set command to it to trick the interpreter into letting the variable escape the sandbox.
#echo off
setlocal EnableDelayedExpansion
set "string=%~1"
for /l %%a in (0,1,10000) do if "!string:~%%a,1!" == "" (
endlocal & set result=%%a
exit /b
)
Does this help you out? The string length is returned as %ErrorLevel%:
New len.bat
#Set "str=#%~1" & SetLocal EnableDelayedExpansion
#Set "len=0" & For /L %%G In (12,-1,0) Do #(Set /A "len |= 1 << %%G"
For %%H In (!len!) Do #If "!str:~%%H,1!" == "" Set /A "len &= ~ 1 << %%G")
#EndLocal & Exit /B %len%
Example test.bat
#Call "len.bat" four
#Echo %ErrorLevel% & Pause
#Call "len.bat" "nineteen inc spaces"
#Echo %ErrorLevel% & Pause
Related
I made this script that finds all directories and echoes the directorie's name to a .txt file. The script is working but it ends up echoing only %A without any value. My script is below!
set /a count=0
setlocal EnableDelayedExtensions
FOR /D %%A in ("*") DO (call :sub)
endlocal
pause
exit
:sub
(echo [DIR] %%A)>>%count%.txt
set /a count+=1
The output in the .txt files is [DIR] %A.
Any idea how to fixe this? Thanks -David
First remark, you are using an invalid option for setlocal but that is probably just a typo.
The problem is that you are try to use a for-parameter where it cannot be used.
The rule is "A for-parameter can only be used within the command or command block () of a for loop"
Your subroutine is not within the command block of a for loop, but you can start a dummy for loop in the subroutine which will give you access to all available for-parameters.
set /a count=0
setlocal EnableDelayedExpansion
FOR /D %%A in ("*") DO (call :sub)
endlocal
pause
exit/b
:sub
For %%. in (.) do (echo [DIR] %%A)>>%count%.txt
set /a count+=1
You need to pass the parameter to the subroutine.
From https://www.informit.com/articles/article.aspx?p=1154761&seqNum=11 :
for %%f in (*.dat) do call :onefile %%f
exit /b
:onefile
echo Processing file %1...
echo ... commands go here ...
exit /b
As you've already enabled delayed expansion, there's no need to use a Call to a label, just do it within the loop.
#Echo Off
SetLocal EnableExtensions EnableDelayedExpansion
Set "count=0"
For /D %%G In (*) Do (
Set /A count += 1
(Echo [DIR] %%G) 1>"!count!.txt"
)
On this version, I've started at 1 instead of 0 for the first text file name, if you really want to start at 0, change line 3 to Set "count=-1"
I have a folder structure, which is like for example C:\Temp\ and there are a lot of folder and file, and within each folder there are a "callme.bat". I would like to create a so called main.bat which is one after another call the callme files within the main' window. But there is a problem, within the callme files are some echo which contains "!" mark what make a problem for me.
I realized the problem with the setlocal-endlocal combo, because the batch scrip wants to interpret the message within the "!" marks, so I must use endlocal, but if I did I not able to run the callme bats.
callme.bat
#echo off
echo !!! hidden message !!! not hidden message
pause
main.bat variant 1
#echo off
setlocal enabledelayedexpansion
set PATH=C:\Temp
for /F %%x in ('dir /B/A:D %PATH%') do (
set CURR_DIR=%PATH%\%%x
set ACTUAL_BATCH=!CURR_DIR!\callme.bat
echo !ACTUAL_BATCH!
call !ACTUAL_BATCH!
pause
)
pause
exit
main.bat variant 2
#echo off
set PATH=C:\Temp
for /F %%x in ('dir /B/A:D %PATH%') do (
setlocal enabledelayedexpansion
set CURR_DIR=%PATH%\%%x
set ACTUAL_BATCH=!CURR_DIR!\callme.bat
echo !ACTUAL_BATCH!
ENDLOCAL & SET VAR=!ACTUAL_BATCH!
echo %VAR%
pause
)
pause
exit
main.bat variant 3
#echo off
set PATH=C:\Temp
for /F %%x in ('dir /B/A:D %PATH%') do (
setlocal enabledelayedexpansion
set CURR_DIR=%PATH%\%%x
set ACTUAL_BATCH=!CURR_DIR!\callme.bat
echo !ACTUAL_BATCH!
REM source: https://stackoverflow.com/questions/3262287/make-an-environment-variable-survive-endlocal
for /f "delims=" %%A in (""!ACTUAL_BATCH!"") do endlocal & set "VAR=%%~A"
echo %VAR%
call %VAR%
pause
)
pause
exit
So I don't know what to do. Anyone has an idea?
variant 1's output:
C:\Temp\1\callme.bat
not hidden message
C:\Temp\2\callme.bat
not hidden message
variant 2-3's output:
C:\Temp\1\callme.bat
ECHO is off.
C:\Temp\2\callme.bat
ECHO is off.
TL;DR
ENDLOCAL&set "varname=%sourcevarname%"
probably, where varname is the variablename to set and sourcevarname is the variable whose value is to be assigned to varname - and they CAN be the same name, even if the statement appears logically null - it's exporting the variable from within the setlocal/endlocal block.
Key point: MUST be on one physical line and may be repeated if necessary (ie
ENDLOCAL&set "varname=%sourcevarname%"&set "varname2=%sourcevarname2%"
So
ENDLOCAL&set "fred=%fred%"&set "bill=%george%"
is perfectly valid, to set the value of fred outside the setlocal/endlocal bracket to its final value inside and of billoutside to the final value of george inside.
Some points about your code:
Never use PATH as a variable name, as it destroys the PATH variable for searching executable files.
Use the extended SET syntax set "varname=content" to avoid problems with trainling spaces.
You only need to disable the delayed expansion mode by using setlocal DisableDelayedExpansion
#echo off
setlocal EnableDelayedExpansion
set MY_PATH=C:\Temp
for /F %%x in ('dir /B/A:D %PATH%') do (
set "CURR_DIR=%MY_PATH%\%%x"
set "ACTUAL_BATCH=!CURR_DIR!\callme.bat"
call :execute ACTUAL_BATCH
pause
)
pause
exit /b
:execute ACTUAL_BATCH
set "batFile=!%~1!"
echo Calling !batFile!
setlocal DisableDelayedExpansion
call %batFile%
endlocal
exit /b
I am trying to write a batch script that does the following:
When a folder is drag-and-dropped onto the batch script, it processes every file in that folder.
I am running into a problem with a certain filenames that contain exclamation marks. e.g.:
!.txt or !!!.txt
For now, I am simply trying to rename the file to demonstrate the issue:
#echo off
SetLocal EnableDelayedExpansion
set folder=%~1
set count=0
for /r "%folder%" %%G in (*) do (
set fullpath=%%G
set fileExtension=%%~xG
call :processFile
)
goto end
:processFile
echo "fullpath = %fullpath%"
echo "fileExtension = %fileExtension%"
rename "%fullpath%" "temporary_filename_500%fileExtension%"
set /a count+=1
echo.
goto :eof
:end
echo "%count% files processed."
pause
It gives me the error "The system cannot find the file specified." However, it works if I change the filename to something simple like "test.webm" How can I make the script more robust?
I don't see that you are using somewhere delayed expansion. So, either disable it with setlocal DisableDelayedExpansion in the start of your batch file or just remove it by removing line setlocal EnableDelayedExpansion.
However, if you want to keep it, do:
#echo off
SetLocal EnableDelayedExpansion
rem Code above (^^) if exists.
Setlocal DisableDelayedExpansion
set "folder=%~1"
set "count=0"
for /R "%folder%" %%G in (*) do (
set "fullpath=%%~fG"
set "fileExtension=%%~xG"
call :processFile
)
goto end
:processFile
echo "fullpath = %fullpath%"
echo "fileExtension = %fileExtension%"
ren "%fullpath%" "temporary_filename_500%fileExtension%"
set /a "count+=1"
echo/
goto :eof
:end
echo "%count% files processed."
pause
setlocal EnableDelayedExpansion
rem Your code below with active delayed expansion:
Note that:
You should always quote the variable name and the value in the set command like set "var=value" and in set /a like set /a "var+=1", etc.; see set /? for more information.
To find the full path of a file/folder for sure in a for loop, use the f modifier, like %%~fG.
Mentioned by Mofi here: don't use echo.; use echo/ for better practice.
See also the Phase 5 (Delayed Expansion) of this answer about how batch files are interpreted.
I want to replace a variable's substring, previously stored on a variable inside a for loop, I tried to do it like this but it didn't work:
setlocal EnableDelayedExpansion
set checkVar=abcd
FOR %%Y IN (*.pdf) DO (
SET meu=%%Y
CALL SET meuWithoutChar=!meu:%%%checkVar%%%=!
ECHO meuWithoutChar=!meuWithoutChar!
)
For example here if %%Y==blepabcdnnnn.pdf; I want to have meuWithoutChar=blepnnnn.pdf on the output
Thank you in advance
You are bit confused on the concept of delayed expansion and the use of CALL to get an extra phase of expansion. Here are the examples. I am just using your single file example. You can change it back to using the wildcard.
CALL example
#echo off
set checkVar=abcd
FOR %%Y IN (blepabcdnnnn.pdf) DO (
SET "meu=%%Y"
CALL SET "meuWithoutChar=%%meu:%checkVar%=%%"
CALL ECHO meuWithoutChar=%%meuWithoutChar%%
)
pause
Delayed Expansion
#echo off
setlocal Enabledelayedexpansion
set checkVar=abcd
FOR %%Y IN (blepabcdnnnn.pdf) DO (
SET "meu=%%Y"
SET "meuWithoutChar=!meu:%checkVar%=!"
ECHO meuWithoutChar=!meuWithoutChar!
)
pause
As a supplement/extension to Squashmans answer.Only cycles through necessary files and ignores the file's extension.
Without delayed expansion:
#Echo Off
SetLocal DisableDelayedExpansion
Set "strChr=abcd"
For %%A In ("*%strChr%*.pdf") Do (Set "objFileName=%%~nA"
Call Set "objNewFile=%%objFileName:%strChr%=%%%%~xA"
Call Echo %%%%objNewFile%%%%=%%objNewFile%%)
Pause
With full script delayed expansion, (will have issues with filenames containing !'s):
#Echo Off
SetLocal EnableDelayedExpansion
Set "strChr=abcd"
For %%A In ("*%strChr%*.pdf") Do (Set "objFileName=%%~nA"
Set "objNewFile=!objFileName:%strChr%=!%%~xA"
Echo %%objNewFile%%=!objNewFile!)
Pause
With toggled delayed expansion, (protects filenames containing !'s):
#Echo Off
SetLocal DisableDelayedExpansion
Set "strChr=abcd"
For %%A In ("*%strChr%*.pdf") Do (Set "objFileName=%%~nA"
SetLocal EnableDelayedExpansion
Set "objNewFile=!objFileName:%strChr%=!%%~xA"
Echo %%objNewFile%%=!objNewFile!
EndLocal)
Pause
I have whittled down a more complex CMD script to the essentials. It reads an input file line by line, unquotes it (if quoted) and writes it out to another CMD file.
The problem is that if the input file contains exclamation marks (! or bang) the character gets stripped out somewhere along the line.
Here is the CMD script, BANG1.CMD:
#echo off
setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
if exist bang2.cmd del bang2.cmd
for /f "tokens=*" %%a in (bang1.txt) do call :doit1 %%a
exit /b
:doit1
set P1=%1
if %P1%. EQU . exit /b
call :unquotex P1 %P1%
echo>>bang2.cmd echo P1:[%P1%]
exit /b
:unquotex
set X=%2
set Q=%X:~0,1%
if "!Q!" EQU ^""" SET X=!X:~1,-1!
set %1=%X%
exit /b
Here is the input file BANG1.TXT:
HelloWorld
"Hello World"
Hello!World
"Hello!World"
The resulting file BANG2.CMD ends up containing this:
echo P1:[HelloWorld]
echo P1:[Hello World]
echo P1:[HelloWorld]
echo P1:[HelloWorld]
The question is, what happened to the embedded bangs? I have tried with and without ENABLEDELAYEDEXPANSION. I have even tried escaping (^) the bangs in the input file, still with no luck.
Is there any way to preserve them?
Thanks.
The problem at all is delayed expansion here.
With delayed expansion, exclamation marks are used to expand variables, but when there is only one exclamation mark in a line it will be removed.
Specially in FOR /F loops delayed expansion is tricky to handle, as the expansion of the FOR parameter is directly affected by the delayed expansion. The only solution is to disable it temporarily.
The next problem is the CALL, you can't transfer content with CALL (without destroying it).
It's better to transfer the variable by reference (only the variable name) and then get the content in the called function.
The last problem in your code are the percent expansions, do not use them
when delayed expansion is enabled, as the delayed expansion is evaluated after the percent expansion an expanded line will be expanded a second time by the delayed expansion.
Sample.
Assume the content of var is Bang!
echo %var% expands to Bang! but then the delayed expansion will evaluate Bang! to Bang.
With echo !var! you simply get Bang!
#echo off
setlocal ENABLEEXTENSIONS ENABLEDELAYEDEXPANSION
if exist bang2.cmd del bang2.cmd
for /f "tokens=*" %%a in (bang1.txt) do (
setlocal DisableDelayedExpansion
set "line=%%a"
setlocal EnableDelayedExpansion
call :doit1 line
endlocal
endlocal
)
exit /b
:doit1
set "P1=!%1!"
if "!P1!" EQU "" exit /b
call :unquotex P1
echo>>bang2.cmd echo P1:[!P1!]
exit /b
:unquotex
set "param=!%~1!"
if "!param:~0,1!" == ^""" (
set "param=!param:~1,-1!"
)
set "%1=!param!"
exit /b
Like this :
#echo off
(for /f "delims=" %%a in ('type bang1.txt') do echo echo P1:[%%~a])>bang2.cmd
Try this:
#echo off
if exist bang2.cmd del bang2.cmd
for /f "tokens=*" %%a in (bang1.txt) do call :doit1 %%a
exit /b
:doit1
set "P1=%1"
if %P1%.==. exit /b
call :unquotex P1 %P1%
echo>>bang2.cmd echo P1:[%P1%]
exit /b
:unquotex
set "%1=%~2"
exit /b
Using parameters, you can get the version without quotes using %~1 instead of %1. If %1 contains "hello world" for example, then %~1 contains hello world. This allows for an easier unquoting mechanism, removing the need for delayed expansion.