I'm trying to let the user enter numbers and if they miss one I want the program to drop an error message. However If not Defined doesn't work.
set /p aa=a11:
set /p ba=a12:
set /p ba=a12:
set /p ab=a21:
set /P bb=a22:
cls
echo antra matrica
echo.
set /p qq=b11:
set /p wq=b12:
set /p qw=b21:
set /P ww=b22:
for %%A IN (%aa%, %ba%, %ab%, %bb%, %qq%, %wq%, %qw%, %ww%) DO IF [%%A]==[] goto error
It ignores the for command. What could i do to make it work when all the variables are enterd blank?
just a different method:
set Count=0
for %%A IN (%aa%, %ba%, %ab%, %bb%, %qq%, %wq%, %qw%, %ww%) DO set /a Count+=1
if %Count% neq 8 goto error
This takes advantage of the fact that an undefined variable would not be processed with for (this was the problem with your original code)
Another advantage is, that now you could tell, how many of the variables were properly defined (if you want to know)
Aacini's solution will work, but two questions remain:
Why didn't "If not defined" work?
and
Why didn't the command you've posted work?
As you've provided it, cmd will interpret the for command as
for %%A in (aas_value, bas_value, abs_value, ...) do if
So had you entered 4,nothing,5,6... then the command line would be
for %%A in (4, , 5, 6...) do if
, and Space are seen as separators, so this would be resolved as
for %%A in (4separatorsequence5separatorsequence6...) do if
hence the missing value - er, goes missing.
If you'd used ...%var%... and if...defined then since 4,5 and 6 are not defined environment variables, you'd get "if not defined" acting unexpectedly (ie "does not work in the manner I expected but have kept to myself")
Another approach would be
for %%A IN ("%aa%", "%ba%", "%ab%",...) DO IF [%%~A]==[] goto error
which would be interpreted as
for %%A IN ("4"separatorsequence""separatorsequence"5",...) DO IF [%%~A]==[] goto error
Here, "4", "", "5" would each be assigned to %%A - including the quotes. The tilde (~) removes the enclosing quotes, so [%%~A] would be evaluated to [] as expected.
Related
like I told in the question I get an unexplainable Syntax error from my Code.
I've bin searching for a program which automatically backups some saves every 5 Minutes. After I hadn't found anything which belongs to my purposes I decided to do it my own.. in Batch.
Here's the code:
#echo off
set name=Backup
for /f "tokens=1-3 delims=/:" %%a in ("%TIME%") do (set mytime=%%a.%%b,%%c)
set mytime=%mytime:~0,8%
set backupname=%name%_%date%_%mytime%
set dir1= (here comes the source directory)
set dir2= (here comes the target directory)
set countvar=1
:start
For /f "tokens=1-3 delims=/:" %%a in ("%TIME%") do (set mytime=%%a.%%b,%%c)
set mytime=%mytime:~0,8%
set backupname=%name%_%date%_%mytime%
set dir2=(here comes the target directory)\%backupname%
echo Backupordner: %backupname%
ROBOCOPY %dir1% %dir2%
if "%countvar%" == "1" (
set VarDir1=%dir2%
)
if "%countvar%" == "2" (
set VarDir2=%dir2%
)
if "%countvar%" == "3" (
set VarDir3=%dir2%
rmdir /S /Q "%VarDir1%"
set VarDir1=%VarDir2%
set VarDir2=%VarDir3%
set /a countvar=%countvar%-1
)
set /a countvar=%countvar%+1
#ping -n 30 localhost> nul
goto start
What it basically does is copying the files from the source directory into a folder, which is named after the date and time, in the target directory.
Caused by the high size of the backuped files I decided to add a feature, which deletes the third oldest save, so there are two remaining, newer save-files.
This is where the problem occurs: The first two "deletes" work properly, the third "delete" causes a syntax error. Everything runs normal after it.
Does anybody have an idea where the problem could be?
Yet another example of the delayedexpansion trap.
When vardir3 is established, it has no value, so vardir2 acquires nothing on the first occasion that count=3
On the second occasion, var1 acquires that value so on the third occasion, you get a syntax error as var1 is empty.
Solution: Forget var3 entirely. In count=3, set var2 to %dir2%.
Please search SO for the many, many articles on delayed expansion.
Also, you're better off using set "var=value" for a string assignment as it does not assign any trailing spaces that may be on the line.
I've no knowledge regarding Windows batch programming syntax. I have a text file containing user IDs which I need to delete using curl command and for that I need to extract first character of every user ID and then pass to the curl command. I know the curl command which will require two variables:
'UserID' - Read from the text file.
'firstCharacter' - Extracting first character from the User ID.
Below is the code to fetch user IDs from users.txt file:
#echo off
for /f "tokens=*" %%a in (users.txt) do call :processline %%a
pause
goto :eof
:processline
echo %*
goto :eof
:eof
Please help me with extracting the first character from the read User IDs.
Thanks.
The cmd.exe can do a limited amount of string parsing. JosefZ gave you a good place to start.
C:>echo %PROCESSOR_ARCHITECTURE%
AMD64
C:>echo %PROCESSOR_ARCHITECTURE:~0,1%
A
In a batch / command file I was always needing the first x characters or a string and ended up with many functions all doing the same thing but different names, i.e. getFirstChar, getFirstTwoChars, etc.. - so decided to make a generic function where I could pass in the number of characters I needed:
::-- getFirstXChars
:getFirstXChars
set sValIn=%1
set /a iNo=%2
set vWorkVal=%%sValIn:~0,%iNo%%%
call:getFirstX %vWorkVal% vWorkVal2
set %3=%vWorkVal2%
:getFirstX
set %2=%~1
goto:eof
to use the syntax would be
set varToTrim=ABCDEFG
call:getFirstXChars %varToTrim% 2 varToTrimAfter
#echo 1 %varToTrim%
#echo 2 %varToTrimAfter%
pause
result from command file:
1 ABCDEFG
2 AB
I just added to set variable "id" to be %%a, then I used substring notation to get the first character.
Substrings are processed by using :~start,length after the variable name and before the last % in the variable.
#echo off
for /f "tokens=*" %%a in (output.txt) do set id=%%a & call :processline %%a
pause
goto :eof
:processline
echo %id:~0,1%
goto :eof
:eof
I'm aware that set zeroThroughNine=%Random%*9/32768 followed by echo %zeroThroughNine% will produce a a random number between and including 0 and 9. But it seems the interpreter doesn't evaluate the contents of the variable every time it is called, and as such, echo %zeroThroughNine% produces, for example, 7 every time.
I looked up a method for running commands using variables so that I could try to force it to work. I liked the question because it was very basal in its approach; something along the lines of "How can I run commands using variables?", tagged appropriately. I didn't much care for the answer because it was very narrow. The highest voted and selected answer was:
Simple. Just run set commandVar=echo "Hello world.", followed by echo %commandVar%.
Of course the truth is that only works for the echo command. >: [
Anyway I'll stop complaining. This is what I've tried:
set zeroThroughNine=set /a number=%Random%*9/32768 & echo %number% followed by echo %zeroThroughNine%
Unfortunately the & echo %number% section of my SET command runs immediately, producing "%number%" as output --and using echo %zeroThroughNine% produces "set /a number=8436*9/32768", for example, as output.
So two questions: How can I universally achieve running commands with the use of variables (or some alternative method), and perhaps more pressing, how can I achieve producing a new random number at the command line with each new command calling?
You should set number before you set zeroThroughNine to the command, like so:
set /a number=%Random%*9/32768
set zeroThroughNine=echo %number%
%zeroThroughNine%
Also, since zeroThroughNine already is an echo command, you don't need to add the extra echo before it.
EDIT:
Taking into account your Random calculation is needlessly complicated, the final code should be something like this (1 - 10 exclusive):
set /a number=%Random% %% 10
set zeroThroughNine=echo %number%
%zeroThroughNine%
Important thing is, rather than trying to do it all on one line, it is much more readable by separating it into two.
The CALL SET syntax allows a variable substring to be evaluated, the CALL page has more detail on this technique, in most cases a better approach is to use Setlocal EnableDelayedExpansion.
Command line (note that all % percent signs are escaped as ^% and that > and & characters are escaped within a pair of " double quotes:
set "zeroThroughNine=call set /a number=^%Random^% ^% 10>nul & call echo number=^%number^%"
%zeroThroughNine%
for /L %G in (1, 1, 10) do #%zeroThroughNine%
Batch script, CALL method (note that all % percent signs are escaped as %%):
#echo OFF
SETLOCAL
set "_zeroThroughNine=call set /a _number=%%Random%% %%%% 10 & call echo number=%%_number%%"
echo check variables
set _
echo output
%_zeroThroughNine%
for /L %%G in (1,1,10) do %_zeroThroughNine%
echo check variables after evaluating
set _
ENDLOCAL
Batch script, EnableDelayedExpansion only for output:
#echo OFF
SETLOCAL EnableExtensions DisableDelayedExpansion
set "_zeroThroughNine=set /a _number=!Random! %% 10 & echo Number=!_number!"
SETLOCAL EnableDelayedExpansion
echo check variables
set _
echo output
%_zeroThroughNine%
for /L %%G in (1,1,10) do %_zeroThroughNine%
echo check variables after evaluating
set _
ENDLOCAL
ENDLOCAL
Batch script, EnableDelayedExpansion script wide (note that ! exclamation sign is escaped as ^!):
#echo OFF
SETLOCAL EnableExtensions EnableDelayedExpansion
set "_zeroThroughNine=set /a _number=^!Random^! %% 10 & echo NUMBER=^!_number^!"
echo check variables
set _
echo output
%_zeroThroughNine%
for /L %%G in (1,1,10) do %_zeroThroughNine%
echo check variables after evaluating
set _
ENDLOCAL
Check out this question. Basically, it's an issue with how the %random% environment variable works...
EDIT:
To elaborate, the reason your random value was always 7 is because of how cmd's pseudo-random number generator works, not because of how the variables are interpreted. The matter is explained very well in this answer.
Essentially, in repeated runs of a batch file, %RANDOM% will produce a value very close to the previous run. Thus, the expression %RANDOM%*9/32768 produces the same result in each separate run because of the random value.
If I understand correctly, the question you're asking is how to better generate a random value 0 - 9 inclusive, which would be by using the following expression:
set /a zeroThroughNine=%RANDOM% %% 10
I'm attempting to access a parameter passed to a function using a variable
name. I know of other ways to do this, such as using the SHIFT command,
but in this case I am trying it this way. I thought by using the
"setlocal enabledelayedexpansion" command I could do this because it permitted
the variable to be accessed using exclamation points around it rather than percent
signs. This is the line from the script below that isn't working:
set parm_value=%!parm_nr!
I thought that this would result in something like this:
set parm_value=%1
but instead, it is resulting in:
set parm_value=1
Does anyone know if this type of syntax is possible? Below is a test
script demonstrating the issue. Everything except this one item is
working correctly. Thank you in advance.
:BOJ
echo off
setlocal enabledelayedexpansion
cls
echo.
call :EXAMPLE_1 parm_1.1 parm_1.2 parm_1.3
goto :EOJ
:EXAMPLE_1
set nr_parms=0
for %%x in (%*) do set /A nr_parms+=1
set parm_nr=1
:EXAMPLE_1_LOOP
if %parm_nr% GTR %nr_parms% goto :EXAMPLE_1_END
set parm_value=%!parm_nr!
echo Parameter #%parm_nr% : %parm_value%
set /A parm_nr+=1
goto :EXAMPLE_1_LOOP
:EXAMPLE_1_END
echo.
exit /B 0
:EOJ
pause
try with
call set parm_value=%%!parm_nr!
So I was tasked with making a batch file that does a few specific things. I've never worked with batch before, and I'm finding it hard to find tutorials on what exactly I need. (I've done basic tutorials)
I'm trying to get the most currently edited file from a directory. The only thing I've came up with (and I've noticed other people said to do) is a for loop of files in the directory sorted by date and then just get the first file and break the loop.
Some problems:
1) My loop never breaks
2) My ECHO %variable% doesn't work at the end.
#echo off
SET count=0
FOR /f %%i in ('DIR Y:\ /B /O:-D') DO (
IF count==0 (
SET NewestFile=%%i
SET count=1
)
)
#echo on
ECHO %NewestFile%
When I run this, I get:
C:\>testing.bat
C:\>ECHO
ECHO is on.
I am 100% new to Batch. Maybe I'm doing something that this is really picky about? (Other StackOverflow questions have been solved by people just adding aa space or stuff like that)
Your condition is never met because the string count is never equal to the string 0. You need
if !count!==0 (
set NewestFile=%%i
set count=1
)
But then you also need delayed expansion (at the beginning of your batch file):
setlocal enabledelayedexpansion
The problem here is that you need to tell the batch file that there is a variable. Like foo in Perl won't magically resolve to the contents of the $foo variable count in your batch file isn't equivalent to %count% (the variable contents) or !count! (the same, but with delayed expansion).
Delayed expansion is necessary because the whole for loop is parsed at once. And cmd replaces normal (%foo%) variables with their contents during parsing so that during execution only the values remain. So once execution reaches the if there would be the condition 0==0 because that's what count's value was before the loop. Delayed expansion (using the !foo! syntax) expands the variables immediately prior to execution, so this does not happen.
For more help on delayed expansion you can read help set.
Another way would be to just use absence or presence of the count variable:
SET count=
FOR /f %%i in ('DIR Y:\ /B /O:-D') DO (
IF not defined count (
SET NewestFile=%%i
SET count=1
)
)
This works around the problem above because there is no variable to replace during parsing. All we're doing is a run-time check whether the variable count exists.
If you supplied accurate code then you want to get the first line - and this is one way to do that.
#echo off
FOR /f %%i in ('DIR Y:\ /B /O:-D') DO SET "NewestFile=%%i" & goto :done
:done
ECHO %NewestFile%
If you change the dir command to list the files in ascending order instead of descending order, you can use this one-liner which doesn't need any of the common bizarre cmd.exe scripting hacks. It just keeps the last line of output in the NewestFile variable (I guess it might qualify as a cmd.exe scripting hack, but I don't think it qualifies as bizarre):
for /f %%i in ('DIR Y:\ /B /O:D') do set NewestFile=%%i