How to stop overwriting but add a new number beside the name.
I tried to make this code, but it didn't work.
set overwrite=0
set newoverwrite=0
:loop
if (%textfile.txt%==EXIST) goto fix
:fix
set /a newoverwrite=%overwrite%+1
if (%textfile%newoverwrite%.txt%==EXIST) goto fix
echo hello > textfile%newoverwrite%.txt
echo skipped!
pause > nul
It is a bit sloppy because I have tested it many times.
Does anyone know how? Or fix my code?
I am assuming you want to create files by just incrementing numbers to it.
#echo off & set cnt=0
:loop
type "textfile%cnt%.txt">nul 2>&1 && echo skipped textfile%cnt%.txt || (echo hello)>"textfile%cnt%.txt"
set /a cnt+=1
pause
goto :loop
I am not sure though if you are aware that this will create files in a permanent loop until you interrupt the process. so Do Not remove the pause from the script.
To explain what it does. We test the file for existance by attemtping to type the file. If the file does exist, type is successful and generates errorlevel of 0. This is where the && conditional operators come into play. If the errorlevel is 0 then it will execute the command after && which is to echo Skipped... However, should the file not exist will it will generate errorlevel of 1 and skip the && operator where the code after || will be executed.
Related
I'm writing a script where a user has to put in a time. The issue I'm running into is that the user can enter anything and batch script will accept it. My idea to check for this was to extract where the colon should be in the time inputted and check if it's there with this:
SET check=%utime:2,1%
IF %check%==: [continue with script]
So that it'd skip the first two characters in say 01:00 and extract the semi colon, set it to check and then compare check to see if it was a colon or not. This works great but then I realized that a user could input anything with a colon in the third space and get past. For a first step my idea to check for this was to have a FOR loop check all the five possible spaces to see if they were empty or not with this code:
SET conf=1
FOR /L %%i IN (1,1,5) DO (
echo %%i
SET check=%utime:%%i,1%
IF [%check%] == [] SET conf=0
)
conf would be a true or false variable (0 or 1) that I could then evaluate with an IF statement to then see if it's a valid format. But what ended up happening is that conf was set to 0 but it was not correctly checking the characters within the time variable. Leaving the echo on I could see that check was not correctly being set meaning conf was always set to 0 no matter what was inputted from the user. Here is the code in question in context just in case (This portion is only meant to check for 5 characters being present):
:Start
SET /p utime=Please insert the time (hh:mm):
CALL :CheckTime
IF conf EQU 1 goto :Valid
ECHO Please enter a valid time!
GOTO :Start
:Valid
ECHO Thank you for entering a valid time!
PAUSE
EXIT
:CheckTime
SET conf=1
FOR /L %%i IN (1,1,5) DO (
echo %%i
SET check=%utime:%%i,1%
IF [%check%] == [] SET conf=0
)
EXIT /B
A little bit different approach then Compo.
:: Q:\Test\2018\06\14\SO_50860883.cmd
#Echo off
:Start
Set "MyTime="
SET /p MyTime=Please insert the time (hh:mm):
If not defined MYTime Exit /B 0
CALL :CheckTime "%MyTime%"|| (ECHO Please enter a valid time! &GOTO :Start)
ECHO Thank you for entering a valid time %MyTime% !
ECHO=
goto :Start
:CheckTime passed value not a fixed var
Echo=%~1|Findstr "^[0-9]:[0-5][0-9]$ ^[0-1][0-9]:[0-5][0-9]$ ^2[0-3]:[0-5][0-9]$" 2>&1>Nul || Exit /B 1
To not allow the input of a single digit hour change the last line to :
Echo=%~1|Findstr "^[0-1][0-9]:[0-5][0-9]$ ^2[0-3]:[0-5][0-9]$" 2>&1>Nul || Exit /B 1
Perhaps using FindStr would be suitable:
:Start
Set "uTime="
Set /P "uTime=Please insert the time (hh:mm): "
Set "uTime=%uTime:~,5%"
If Not Defined uTime GoTo :Start
Echo %uTime% |FindStr /R "[0-1][0-9]:[0-5][0-9] 2[0-3]:[0-5][0-9]">Nul||GoTo :Start
Echo Thank you for entering a valid time!
Pause
I'm facing an issue when trying to implement the ERRORLEVEL on my batch script. Basically what I'm trying to do is: look for the .txt files in the directory and if found; .txt will get listed, if not found; message error will occur.
The thing is that this directory will not always contain a .txt, sometimes it will be empty and when that happens my code will not work. Only when there is a .txt in the directory I'm getting my conditions to work (ERRORLEVEL = 0), but if empty; none of my conditions will. Not even the ERRORLEVEL will be printed in the cmd screen (I should see it as ERRORLEVEL = 1).
This is my code:
for /r "C:\Texts" %%a in (*.txt) do (
echo %errorlevel%
IF ERRORLEVEL 0 (
echo %%a
echo "I found your Text!"
) ELSE (
echo "I couldn`t find your Text!" )
)
What exactly is wrong with my ERRORLEVEL implementation?
Errorlevel 0 is always true.
Use
if not errorlevel 1
But your code doesn't set the errorlevel.
In your code there is not any command that set the errorlevel. This value is set by all external .exe commands (like find or findstr), and by certain specific internal commands (like verify that set errorlevel=1 when its parameter is wrong, or ver that always set the errorlevel=0.
You may explicitly set this value in your code this way:
rem Set the errorlevel to 1
verify bad 2> NUL
for /r "C:\Texts" %%a in (*.txt) do (
echo %%a
rem Set the errorlevel to 0
ver > NUL
)
if not ERRORLEVEL 1 (
echo "I found your Text!"
) else (
echo "I couldn't find your Text!"
)
However, you may also get a similar result using a Batch variable instead of the errorlevel...
So i am attempting to make a simple script to check if an application is running using a external text file (using 1 and 0 for if running or is not). However i cannot seem to get the statement working correctly..
setlocal enabledelayedexpansion
set /p Running=<IsRunning.txt
IF %Running% EQU 0(GOTO ProgramNotRunning)
IF %Running% EQU 1(GOTO ProgramRunning)
:ProgramNotRunning
echo program starting
echo 0 >IsRunning.txt
echo 1 >IsRunning.txt
GOTO:EOF
:ProgramRunning
echo program already running
GOTO:EOF
The issue is no matter what value it is, it always only ever runs the ProgramNotRunning code block and not the other.
Prior to using EQU, i was simply using == to check for equivilance.
Much thanks for any assistance given!
1 - Missing spaces
If %Running% EQU 0 (...
^ This space is needed
2 - In batch files lines of code are executed one after the other unless one command changes this behaviour. You can iterate with for, jump with goto, call subroutines with call, leave the batch, the subroutine or the console with exit, ... but a label will not break the execution. After your if %Running% EQU 1 ... there isn't anything that prevent execution to continue into the code following code it none of the if tests find a coincidence. So, if the set /p does not retrieve 0 or 1 the code after :ProgramNotRunning will be always executed.
3 - Missing/empty file. If IsRunning.txt can not be found or it is empty (or at least the first line is empty) or if it does contain an unexpected value, the if lines will fail. The code executed is
file missing : if EQU 0 (
line/file empty : if EQU 0 (
bad data : if this is a test EQU 0 (
All this cases will cause the line to be considered an error and the execution will be canceled.
#echo off
setlocal enableextensions disabledelayedexpansion
rem Retrieve running state
set "Running="
if exist "IsRunning.txt" (
set /p "Running=" < "IsRunning.txt"
)
IF "%Running%" EQU "0" goto ProgramNotRunning
IF "%Running%" EQU "1" goto ProgramRunning
rem As there is no valid data, assume the program is not running
:ProgramNotRunning
echo program starting
>"IsRunning.txt" (echo 1)
goto :eof
:ProgramRunning
echo program already running
goto :eof
Why >"IsRunning.txt" (echo 1)? Just to be sure there are no aditional spaces after the 1 that will be included in the output (as happens with your code), retrieved when the line is readed from the file and causing the if to fail
if "1 " EQU "1" ( ... This will be evaluated to false
And this still leaves cases where the data retrieved can make the code fail. For a 0/1 test, it is easier to not read the file, just test for presence of the file. If the file exist, the program is running, else it is not running.
Is there any code system like below :
#echo off
set /p location=Type Folder Location
copy "%location%\file.txt" "c:\Folder"
if copy is done goto ok
if not goto failed
:ok
echo File is copyed succesfully
:failed
echo File is not copyed
echo.
pause
exit
#echo off
set /p location=Type Folder Location
copy "%location%\file.txt" "c:\Folder"
if errorlevel 1 goto failed
:ok
echo File is copied succesfully
goto done
:failed
echo File is not copied
:done
echo.
pause
exit
Normally, when a command succeeds, the "magic" variable errorlevel is set to zero; if it fails, to non-zero.
The syntax if errorlevel n will be true if errorlevel is n or greater than n (this last point is important - if errorlevel 0 will always be true (in normal circumstances).
Unlike many languages, batch has no concept of the end of a "procedure" - it simply continues execution line-by-line until it reaches the end-of-file. Consequently, you need to goto :eof after completing the mainline, otherwise execution will continue through the subroutine code. :EOF is a predefined label understood by CMD to mean end of file. The colon is required.
(in this case, the goto done skips over the 'failed' message - often you want to terminate the batch under certain circumstances. there you'd use goto :eof)
Like #Magoo saids in your case you just need 1 condition to go forward.
But to answer your question: How to mention If else condition in batch file
#echo off
set /a $var=1
if %$var%==1 (goto:ok) else (goto:nok)
:ok
echo OK
exit/b
:nok
echo NOK
You can change the value of $var to check it
I am attempting to make a script that is called from another script to update him...
This script is downloaded from a server via wget and it is started by other script. It checks version of RunToolkit and, if it isn't v1.1, it downloads the new version...
But when this script is called, it give an error, "unexpected goto".
Hers is the script:
#echo off
echo Latest version is 1.1
:restart
IF EXIST RunToolkit.exe (
FIND /I "1.1" "RunToolkit.exe" > NUL:
IF ERRORLEVEL 0 (
ECHO Your toolkit version is 1.1
echo No updates available!
PAUSE
goto quit
) ELSE (
ECHO Your toolkit is outdated, do you want to update it?
ECHO.
ECHO 1. Yes
ECHO 2. No
ECHO.
SET /P menunr=Select number you want :
IF %menunr%==1 (goto yesupdate)
IF %menunr%==2 (goto quit)
goto what
)
)
:yesupdate
echo Downloading new version!
wget (link deleted for privacy :P)
:what
echo.
echo You entered a wrong number! Retry!
PAUSE
goto restart
:quit
call RunToolkit.exe
Can anyone find the error, please?
First issue, nothing to do with your error is
IF ERRORLEVEL 0 (
Which should alwaays be true. if errorlevel n means if errorlevel is n OR GREATER THAN n. There ARE ways of setting errorlevel negative - but normal operation would always set a positive errorlevel, hence if errorlevel 0 should always be true.
Your next problem is that CMD always substitutes the current value for any %var% in any logical line, then validates the line. The logical line here starts at IF EXIST and runs through to the single closing-parenthesis in the first column - 18 physical lines later.
At that time, IF %menunr%==1 (goto yesupdate) will be evaluated as IF ==1 (goto yesupdate) because menunr is undefined WHEN THE LINE WAS PARSED. This is the source of your UNEXPECTED GOTO
Since you are entering memunr you need to learn about delayedexpansion - here's a demo:
#echo off
SETLOCAL
cls
set var=ORIGINAL
echo Start value of var=%var%
for %%i in (1) do (SET var=AFTER
ECHO var is %var% in the for loop
)
echo Final value of var=%var%
ENDLOCAL
ECHO.
echo ---- try again with ENABLEDELAYEDEXPANSION
ECHO.
setlocal enabledelayedexpansion
set var=ORIGINAL
echo Start value of var=%var%
for %%i in (1) do (SET var=AFTER
ECHO var is %var% not !var! in the for loop
ECHO Note: in the loop VAR has old value %var% and new value !var!
)
echo Final value of var=%var%
endlocal
Note the difference between %var% (the PARSE-TIME value) and !var! (the RUN-TIME value)
ALSO:
If you press simply ENTER as a response to SET /P menunr=Select number you want : then menunr will remain UNCHANGED. Since it had no value, it will still have no value, and hence if you turn on delayedexpansion by mans of a setlocal enabledelayedexpansion statement, the logical change
IF %menunr%==1 (goto yesupdate)
to
IF !menunr!==1 (goto yesupdate)
will also suffer the same error.
You need to use
IF "!menunr!"=="1" (goto yesupdate)
to cater for the empty-variable scenario.
(also: the parentheses around the GOTO here are superfluous, but harmless)