Writing a variable with the value 0 into a file (Batch) - batch-file

i'm trying to write an integer to a file using redirection in batch,but i can't seem to do it.All i get is empty lines.
set var_1=0
echo %var_1%>output.txt
The same happens when i try to write numbers directly without declaring a variable first.
although this is not the case when i use two digit numbers or more.
Any solution to this?
Already tried
set var_1=100
set /a var_1=0
echo %var_1%>output.txt
Didn't know why i even tried this but i did it and the problem persist.
Thank you in advance.
Update : * I've already found a solution to this after a lot of searching *
For those who are interested to the solution and explaination :
http://www.dostips.com/forum/viewtopic.php?f=3&t=4668

Problem with a digit directly before the redirector.
try
>filename echo 0
1>nul redirects standard output to nul (suppresses output)
2>nul redirects standard error to nul (suppresses error messages)
0 is standard input
3..9 similarly affected, nul can be a filename if desired.

If you try this at the console you see what is going on , you get something like
ECHO is on (aan).
Which means your 0 is neglected because the console sees it as a kind of null.
Use this instead, the space does the trick
echo %var_1% > output.txt

Related

Store return value of a compiled exe into a batch variable

I've read topics here and on the internet about the argument but the solutions offered do not work for me.
Firstly I'll tell you what I want to do:
I have a compiled c file (.exe) that returns various integers depending on the situation.
I want to store said return value in a variable in batch. From what I've read, there's no specific command to do this (like 'v=$?` in shell that assigns to the variable the last returned value), but I found instead a workaround that uses the for loop.
The code I found is the following:
FOR /F "tokens=*" %%a in ('test.exe') do SET OUTPUT=%%a
echo %OUTPUT%
But when I run the batch file, I get ECHO is off.
I'm a complete beginner in batch, I simply searched "store return value in batch" and the code above is what got spit out. Any insight or help on the problem is appreciated, thanks in advance!
Answer given by Mofi
Dillon Wreek wants the exit code (also called exit value, return
value, return code or in CMD syntax errorlevel) of test.exe and not
the output of the text.exe written to handle stdout. So all needed by
Dillon Wreek is a batch file with first line #echo off, second line
test.txt, third line echo %errorlevel% resulting in writing into
console window the value 1 or 2 or 3 or ... 12 and fourth line pause
to see the output on double clicking on batch file.
Basically:
test.exe
set var=%errorlevel%
echo %var%

IF command not working when using 'NOT or '==' to use CALL and use SET for setting a variable

I'm creating a simple program that will echo variables from SET /p strings into a nice, neat list. However, I am having trouble creating 2 working IF statements, one using NOT, and one using == to detect if one of my variables, %pwad%, is empty, or contains values. I want to use what the IF statement returns to set variable %finalpwad% to either "No pwad detected" or %pwad%.
How should I properly write this statement? Where might I need corrections, fixing the IF statements or maybe even the part where it sets %pwad% to %finalpwad%?
I have already tried fixing my call part and what they call from, but to no avail. I'm almost sure this is an IF statement issue, as I'm not too good with them, and always struggle reading the notes about the command from IF /?.
Here's a snippet of my code and the source of the problem I am having:
set /p pwad=Set a pwad (or none):
if %pwad% NOT [] call :yespwad & pause
if %pwad% == [] :nopwad & pause
:nopwad
set finalpwad=No pwad detected
goto :printout
:yespwad
set finalpwad=%pwad%
goto :printout
I expect the output to continue onto :printout, where it echoes all the variables the user enters, but it instead exits the program, and makes it so I can't find out whether it properly read my IF NOT or IF == statements. I rudimentarily added pauses to snuff out the problem and see where the source was, and I concluded it must the IF statements.
The help file clearly shows the proper syntax for comparing strings.
IF [NOT] string1==string2 command
It is recommended that you use quotes as well when comparing strings.
IF "string1"=="string2" command
IF comparisons are literal. Each side of the comparison has to match. Using brackets does not check for an empty string.
There also is an option to check if a variable is defined.
IF DEFINED VAR command
Looking at your logic you could essentially do this:
#echo off
set /p "pwad=Set a pwad (or none): "
IF DEFINED pwad (
set "finalpwad=%pwad%"
) ELSE (
set "finalpwad=No pwad detected"
)

Batch File: Output variable to text file

I would like to output a variable to a text file. I have done this in my code, but I have one output within an if statement that I can't get to work.
if not exist "%TuningLog%" (
set Title=Tuning Parameters Saving Log
set LogTitle=--------- %Title% ---------
echo %LogTitle%>> "%TuningLog%"
)
All its supposed to do is check first for the existense of a log file and if it doesn't exist then I want to in the first instance append a title.
But all I get in the log file is " echo is off." If I don't use a variable and just place text there then it works fine.
Can anybody spot the problem? Thanks for reading and for any help!
UPDATE:
I changed my code to. I don't know much about delayed expansion, but I tried this and it happened to work...
if not exist "%TuningLog%" (
setlocal enabledelayedexpansion
set Title=Tuning Parameters Saving Log
set LogTitle=--------- !Title! ---------
echo !LogTitle!>> "!TuningLog!"
endlocal
)
If anyone can provide a reason as to why the first attempt didn't work and this did, then please inform this thread for the purposes of learning. Thank you!
because or early expansion. your variable gets replaced with its value at the moment the block starts. at this time, it is still undefined and thus empty. if you have echo on, you can watch this happening on screen. if you enable delayed expansion, as you did in your second example, it gets only expanded at the moment it is used, so it works as you expect variables to work in "real" programming languages.
EnableDelayedExpansion
causes Variables to be expanded in simple language it causes the system to treat the value of variable and not the variable name itself

Batch not-equal (inequality) operator

According to this, !==! is the not-equal string operator.
Trying it, I get:
C:\> if "asdf" !==! "fdas" echo asdf
!==! was unexpected at this time.
What am I doing wrong?
Try
if NOT "asdf" == "fdas" echo asdf
Use NEQ instead.
if "asdf" NEQ "fdas" echo asdf
I know this is quite out of date, but this might still be useful for those coming late to the party. (EDIT: updated since this still gets traffic and #Goozak has pointed out in the comments that my original analysis of the sample was incorrect as well.)
I pulled this from the example code in your link:
IF !%1==! GOTO VIEWDATA
REM IF NO COMMAND-LINE ARG...
FIND "%1" C:\BOZO\BOOKLIST.TXT
GOTO EXIT0
REM PRINT LINE WITH STRING MATCH, THEN EXIT.
:VIEWDATA
TYPE C:\BOZO\BOOKLIST.TXT | MORE
REM SHOW ENTIRE FILE, 1 PAGE AT A TIME.
:EXIT0
!%1==! is simply an idiomatic use of == intended to verify that the thing on the left, that contains your variable, is different from the thing on the right, that does not. The ! in this case is just a character placeholder. It could be anything. If %1 has content, then the equality will be false, if it does not you'll just be comparing ! to ! and it will be true.
!==! is not an operator, so writing "asdf" !==! "fdas" is pretty nonsensical.
The suggestion to use if not "asdf" == "fdas" is definitely the way to go.
Try:
if not "asdf" == "fdas" echo asdf
That works for me on Windows XP (I get the same error as you for the code you posted).
NEQ is usually used for numbers and == is typically used for string comparison.
I cannot find any documentation that mentions a specific and equivalent inequality operand for string comparison (in place of NEQ). The solution using IF NOT == seems the most sound approach. I can't immediately think of a circumstance in which the evaluation of operations in a batch file would cause an issue or unexpected behavior when applying the IF NOT == comparison method to strings.
I wish I could offer insight into how the two functions behave differently on a lower level - would disassembling separate batch files (that use NEQ and IF NOT ==) offer any clues in terms of which (unofficially documented) native API calls conhost.exe is utilizing?
The easiest way I found is to:
IF %ERRORLEVEL% NEQ 0 Echo An error was found
or
IF %ERRORLEVEL% GRT 0 goto error1
The operator !==! has not right value, which means that's used only to know whether a variable was set or not.
IF !%1==! GOTO main

How to create empty text file from a batch file?

Can somebody remember what was the command to create an empty file in MSDOS using BAT file?
copy NUL EmptyFile.txt
DOS has a few special files (devices, actually) that exist in every directory, NUL being the equivalent of UNIX's /dev/null: it's a magic file that's always empty and throws away anything you write to it. Here's a list of some others; CON is occasionally useful as well.
To avoid having any output at all, you can use
copy /y NUL EmptyFile.txt >NUL
/y prevents copy from asking a question you can't see when output goes to NUL.
echo. 2>EmptyFile.txt
This redirects output stream 2 (stderr) to a file. The command echo doesn't output anything to stderr, so the file becomes empty.
Plain echo would work too, but echo. is better because it doesn't print the useless and potentially confusing message ECHO is on.
type NUL > EmptyFile.txt
After reading the previous two posts, this blend of the two is what I came up with. It seems a little cleaner. There is no need to worry about redirecting the "1 file(s) copied." message to NUL, like the previous post does, and it looks nice next to the ECHO OutputLineFromLoop >> Emptyfile.txt that will usually follow in a batch file.
Techniques I gathered from other answers:
Makes a 0 byte file a very clear, backward-compatible way:
type nul >EmptyFile.txt
idea via: anonymous, Danny Backett, possibly others, myself inspired by JdeBP's work
A 0 byte file another way, it's backward-compatible-looking:
REM. >EmptyFile.txt
idea via: Johannes
A 0 byte file 3rd way backward-compatible-looking, too:
echo. 2>EmptyFile.txt
idea via: TheSmurf
A 0 byte file the systematic way probably available since Windows 2000:
fsutil file createnew EmptyFile.txt 0
idea via: Emm
A 0 bytes file overwriting readonly files
ATTRIB -R filename.ext>NUL
(CD.>filename.ext)2>NUL
idea via: copyitright
A single newline (2 bytes: 0x0D 0x0A in hex notation, alternatively written as \r\n):
echo.>AlmostEmptyFile.txt
Note: no space between echo, . and >.
idea via: How can you echo a newline in batch files?
edit It seems that any invalid command redirected to a file would create an empty file. heh, a feature!
compatibility: uknown
TheInvisibleFeature <nul >EmptyFile.txt
A 0 bytes file: invalid command/ with a random name (compatibility: uknown):
%RANDOM%-%TIME:~6,5% <nul >EmptyFile.txt
via: great source for random by Hung Huynh
edit 2 Andriy M points out the probably most amusing/provoking way to achieve this via invalid command
A 0 bytes file: invalid command/ the funky way (compatibility: unknown)
*>EmptyFile.txt
idea via: Andriy M
A 0 bytes file 4th-coming way:
break > file.txt
idea via: foxidrive thanks to comment of Double Gras!
REM. > empty.file
If there's a possibility that the to be written file already exists and is read only, use the following code:
ATTRIB -R filename.ext
CD .>filename.ext
If no file exists, simply do:
CD .>filename.ext
(updated/changed code according to DodgyCodeException's comment)
To supress any errors that may arise:
ATTRIB -R filename.ext>NUL
(CD .>filename.ext)2>NUL
One more to add to the books - short and sweet to type.
break>file.txt
break>"file with spaces in name.txt"
fsutil file createnew file.cmd 0
You can use a TYPE command instead of COPY. Try this:
TYPE File1.txt>File2.txt
Where File1.txt is empty.
There are infinite approaches.
Commands that output nothing:
break
cls
color
goto
pushd
popd
prompt
title
Weird Commands:
CD.
REM.
#echo off
cmd /c
START >FILE
The outdated print command produces a blank file:
print /d:EMPTY_TEXT_FILE nul
You can also use SET to create a null byte file as follows
set x=x > EmptyFile.txt
Or if you don't want to create an extra variable reassign an existing variable like
set PROMPT=%PROMPT% > EmptyFile.txt
or like this:
set "PROMPT=%PROMPT%" > EmptyFile.txt
The easiest way is:
echo. > Filename.txt
IMPORTANT:
If you don't set the encoding, many softwares can break. git is a very popular example.
Set-Content "your_ignore_file.txt" .gitignore -Encoding utf8 this is case-sensitive and forces utf8 encoding!

Resources