Batch Script excueting unchosen block of code - batch-file

I have a batch script that checks the input of the user before running a specific block of code. Both blocks manipulate the same variables but it appears the variables of the second block are the ones that are being set even if I choose the first block to execute.
Code:
if %x == 1 goto :Block1
if %x == 2 goto :Block2
:Block1
set variable== "Works"
:Block2
set variable == "Works"
Block 2 is executing even if I input 1. Am I missing something?

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.

Related

Executing batch file breaks when checking if variable has value

To chcek if file is loaded or not, I load its contents using:
set /p filevar=file.txt
and check if var is empty:
if "%filevar%"="" exit
When script chceks file with multiple lines, execution of script stops, so i suppose that chcecking fails. Why script fails? How to perform such check properely?
Firstly, you've got the syntax of your set /p command messed up. As it is, it will prompt the user with the text "file.txt". I think what you mean is
set /p "filevar=" <file.txt
You should also use the /b switch with exit to prevent the console window from closing if your script is run from the command line.
But yeah, as jeb states, to check whether left equals right, either use == or equ. Or, as dbenham reminds me, if you're checking for an empty value, you can also use if not defined.
if "%filevar%"=="" exit /b
if "%filevar%" equ "" exit /b
if not defined filevar exit /b
All three statements will have the same result1.
In a console window, enter help if for more information.
1 It's worth mentioning that, while those three if statements have the same result outside of a parenthetical code block, only the third one will work reliably within parentheses (such as in a for loop). The first two would need delayed expansion to work properly if used within the same code block as %filevar% is set.

Set one variable in another batch file

I would like to set a variable in another batch file, if it exsists. But it works only localy in the sub batch file. How can I fix this problem?
Main.bat:
SET TEMP=""
IF EXIST SUB.bat (
CALL SUB.bat
REM Returns: TEMP="" IN MAIN
ECHO %TEMP% IN MAIN
) ELSE (
SET TEMP="DEFAULT VALUE"
)
Sub.bat:
SET TEMP="OTHER VALUE"
REM Returns: TEMP="OTHER VALUE" IN SUB
ECHO %TEMP% IN SUB
Output by calling Main.bat:
TEMP="OTHER VALUE" IN SUB
TEMP="" IN MAIN
Two issues:
Your test is incorrect. Within a block statement (a parenthesised series of statements), the entire block is parsed and then executed. Any %var% within the block will be replaced by that variable's value at the time the block is parsed - before the block is executed - the same thing applies to a FOR ... DO (block).
Hence, IF (something) else (somethingelse) will be executed using the values of %variables% at the time the IF is encountered.
Try using CALL ECHO %%TEMP%% to display the altered value and look up "delayedexpansion" for endless SO items on this frequently-encountered subject.
Second issue - which impinges on the first.
TEMP and TMP are special variablenames which specify the location of a temporary-files directory. Best not to change them as unexpected results may ensue. Use another variablename.

Batch If statement not working

Having a problem with an If statement in a batch file. I have several scripts, one will set a value to variable and store it to a text file to be read by another script. The value is either yes or no. That part works. When the next script executes, it first reads the line from the txt file and stores the value to a variable. That part works, I can echo the variable and see that it reads the line and stores it to the variable. Now, the next section is suppose to evaluate the variable and based on the result the script will either continue or exit. for some reason it always exits. Below is sample of the statement:
::****Check Value******
set /p _xexit=<xclean.txt
Echo %_xexit%
if %_xexit%=yes (
goto skip3
) else (
::CODE TO EXECUTE IF %_xexit%=no starts here
code
::AFTER THIS CODE EXECUTES, SCRIPT WILL EXIT
::My skip3
:skip3
echo "Exit Called"
wait
Exit
You have to double the =
if "%_xexit%"=="yes"

Storing multi-word strings to a file

I've recently been trying to make a program to simply store text to a file for later viewing, storing it as a .rar file for security against those who don't understand how to extract the text from the .rar (i.e. the less "techy" people)...
I have, however, encountered an error in the program that results in the <word> not expected at this time followed by the .exe closing when I input add/<word> <word>... (i.e. any multi-word string with spaces in between the words [add/<word>, however, does function properly]).
Is there a special rule that must be followed for storing multi-word strings to a .rar or a file in general (I do, however, know that there is a rule for creating/renaming folders/directories)?
The Program Segment:
:command
cls
set /p journal=<journal.rar
echo %journal%
echo.
set /p command=What would you like to do?
cls
if %command%==exit exit
if %command%==help goto help
if %command%==delete echo START; > journal.rar
if %command:~0,4%==add/ echo "%journal%""%command:~4%;" > journal.rar
if %command:~0,5%==edit/ echo %journal:%command:~5%=%;" > journal.rar
goto command
Excuse me. Your question is not clear. There are several confusing points in it, like "followed by the .exe closing" (which .exe is closing?), and the fact that your question is NOT related to .rar files in any way, nor to "storing multi-word strings". However, I can see the following points in it:
When a variable value is expanded with percent signs this way: %command% you must be aware that the variable is first expanded and then the resulting line is parsed. This mean that the value of the variable may introduce errors in the line. For example, in this line: if %command%==exit exit, if the value of command variable is add/one two three, then the line that is parsed is this: if add/one two three==exit exit that, of course, issue an error! (type if /? for further details).
The way to avoid this problem is enclosing both the variable and the comparison value in quotes; this way, if the value have several words with spaces, the whole value is grouped in the IF command for comparison purposes: if "%command%" == "exit" exit. This must be done in every IF command that use the value of the variable.
In the following line:
if %command:~0,5%==edit/ echo %journal:%command:~5%=%;" > journal.rar
you must be aware that the line is parsed from left to right; this means that you can not nest a %variable% expansion inside another one. The way to solve this problem is first complete a %normal% variable expansion, and then a !delayed! variable expansion that will take the previous expanded value. To do that, insert this line at beginning of your program:
setlocal EnableDelayedExpansion
and change previous line by this one:
if "%command:~0,5%" == "edit/" echo !journal:%command:~5%=!;" > journal.rar
For further details, type set /? and carefully read the sections about "delayed expansion".
Here is a sample that can accept multiple words:
set "command="
set /p "command=What would you like to do? "
cls
if /i "%command%"=="have lunch" goto :food

Batch Files third "If NOT" statement not reached

Hello stackoverflow community,
I am writing a batch file to do some automatic computer maintenance and have included several antivirus applications. For some reason, the third "if not" statement is never reached.
:AV
REM MSE
if not '%MSE%'=='' (
Echo Scanning for viruses using Microsoft Security Essentials.
Echo.
%MSE% -Scan -ScanType 1
Echo.
GOTO Defrag
)
REM AVG
if not '%AVG%'=='' (
Echo Scanning for viruses using AVG.
Echo.
%AVG% /COMP /QT /TRASH
Echo.
GOTO Defrag
)
REM NOD32
if not '%NOD32%'==''(
Echo Scanning for viruses using NOD32.
Echo.
if '%NOD32%'=='' GOTO NOD32NotFound
%NOD32% /aind /auto /log-file="%userprofile%\Desktop\Scan_Results.txt"
Echo.
GOTO Defrag
)
REM If all else fails...
GOTO AVNotFound
Currently, there are three blocks of codes, one for each antivirus program. Each block of code is executed only when the variable %AVG% %MSE% or %NOD32% is not empty, meaning they point to a valid file. I assign the variables using the code:
if exist "%programfiles(x86)%\AVG\AVG2012\avgscana.exe" set AVG="%programfiles(x86)%\AVG\AVG2012\avgscana.exe"
All three blocks of code works perfectly, nothing is wrong with the coding. The problem is that whatever the third block is, it never executes. So in the current example, the blocks of code go in the order of MSE, AVG, and NOD32. NOD32's block of code does not execute because it's the third block. Conversely, if I cut and paste the blocks into another order with AVG's block of code being the third block, it would not execute.
Any ideas?
Any suggestions?
Edited for clarification.
You're missing a space in the line:
if not '%NOD32%'==''(
Try:
if not '%NOD32%'=='' (
When I tried the script this line caused a failure. After changing the line, it worked.
Are the variables %MSE%, %AVG% or %NOD32% batch files? If yes, you will need to invoke them using "call" instead (for example call %AVG%)
If you call a batch file from another, the first one will exit after executing the 2nd one, unless it is called with "call".
Do any of your %AVG%, %NOD32%, or %MSE% variables have brackets in them? Could they be in the C:\Program Files (x86)\ path? A bracket will close the branch prematurely.
Place quotes around the executable part of the commands, for example:
"%MSE%" -Scan -ScanType 1

Resources