Putting output file into var - batch-file

I have easy .bat file
%2 >file.tmp
set /p %1=<file.tmp
I expect to use this script in this way:
putVar var1 command.bat
It should get first line of output command.bat into variable var1
and after that I should be able use var1 variable, for example
putVar var1 command.bat
echo %var1%
Unfortunately this do not work.
How to get this work? Maybe there is some easier way?

Your problem is that in your sample code the command you are running (command.bat) is a batch file, which it is being invoked from inside a batch file, and if from a batch file you call another batch file without using call command, then the execution does not return to caller batch.
To keep the syntax, you can use
(cmd /c "%~2")>file.tmp
set /p "%~1="<file.tmp
spawning a second instance of cmd to handle the command, redirecting its output to the temporary file and then reading the file (only the first line of command.bat output) into the variable.
A simpler way of doing it is to use for /f
for /f "delims=" %%a in ('%~2') do set "%~1=%%a"
which, more or less, do the same work. Run the command retrieve the output and, in this case, iterate over the output of the command, assigning each of the lines of command.bat output to the variable. Obviously, only the last line will be stored inside the variable, as the loop will overwrite its value in each iteration.

Related

Novice Batch Issue- Creating Files

I was working on developing a batch program that would scan various sections of a PC, and log them to a file. Surprisingly, I was unable to have the program create the file to write to. I then tried to create a file, that I was fairly certain would work; it is as followed:
#echo off
ipconfig > ip.txt
timeout 5
However, this was also unable to write to the file ip.txt. I also attempted the following program, with no success.
#echo off
echo Test > test.txt
timeout 3
If anyone would be able to give advice, I would much appreciate it.
No error messages are present, and clicking the link batch file
Issue Resolved, downgraded to Win7 from Win10 and no longer experiencing the issue. Not a great fix.
ipconfig > %userprofile%\desktop\ip.txt
Use full paths. This specifies your desktop as the place to put the file.
See Set /? for help and type set to see standard variables.
& seperates commands on a line.
&& executes this command only if previous command's errorlevel is 0.
|| (not used above) executes this command only if previous command's =
errorlevel is NOT 0
> output to a file
>> append output to a file
< input from a file
| output of one command into the input of another command
^ escapes any of the above, including itself, if needed to be passed =
to a program
" parameters with spaces must be enclosed in quotes
+ used with copy to concatinate files. E.G. copy file1+file2 newfile
, used with copy to indicate missing parameters. This updates the files =
modified date. E.G. copy /b file1,,
%variablename% a inbuilt or user set environmental variable
!variablename! a user set environmental variable expanded at execution =
time, turned with SelLocal EnableDelayedExpansion command
%<number> (%1) the nth command line parameter passed to a batch file. %0 =
is the batchfile's name.
%* (%*) the entire command line.
%<a letter> or %%<a letter> (%A or %%A) the variable in a for loop. =
Single % sign at command prompt and double % sign in a batch file.

redirecting a stream for the entire .bat file inside itself

I've recently started working with .bat files, and I'm trying to redirect the output to a file.
I've found 2 options, so far:
echo aaa > out.txt - which sends the output of the single echo command to the specified file (can also be appended using >>)
calling the entire file from the cmd using somefile.bat > out.txt (which is actually similar to number 1, as it sends the output of the single command somefile.bat to out.txt)
What I'm looking for is something else - I'm trying to have a line in my file that sends all the output from that point forth to the file.
Thanks!
echo this goes to screen
(
echo this line goes to the file
echo also this line and the ping-output
ping www.stackoverflow.com
echo and this
)>file.txt
echo this goes to screen again
Note:
all inside the block (between ( and )) is parsed at once. If you use variables inside the block, you may need delayed expansion.
There is no universal solution. It depends of the batch file requirements.
For a lot of batch files, the answer from Stephan will work without problems, taking in consideration what he pointed: all the code is inside a block and any variable management inside it may require delayed expansion.
Other alternative is to move the code under a subroutine, calling it with the redirection
#echo off
call :mainProcess %* > outputFile
exit /b
:mainProcess
:: here the batch file begins
echo %1 %2 %3

How to redirect a command that contains a variable to be outputed to a variable on the Windows commandline

I want to assign the output of running a batch script with arguments to a variable. Please suggest me on how to do this.
Example:
The output of datemath.bat %Date_Pattern% - 2 should be assigned to a variable.
Say my date_pattern was 2013 05 03 then my variable will come up with 2013 05 01
There are generally two ways to store the output of a command into a variable. I'm going to assume there is only one line of output to be captured. I'm also assuming the output is on stdout, and not stderr. The command could be a call to a batch file, a call to a subroutine within a batch file, an internal command, a standard external command (executable), or a 3rd party executable - the process for capturing the output into a variable is the same.
1) Redirect the output to a temporary file, and then read the value into a variable using SET /P
call dateMath.bat %Date_Pattern% - 2 >output.tmp
<output.tmp set /p "result="
del output.tmp
Typically the temporary file is created in the %TEMP% folder, but I kept everything in the current directory just for simplicity.
People generally like to avoid temporary files if possible, although sometimes that is the best option.
2) Use FOR /F to capture the output directly, without using a temporary file. FOR /F is a complicated command with many options. It is designed to parse input into delimited tokens. The default delimiter is a space; but you want the entire string to be captured in one variable. So you need to set the delimiter to nothing. FOR /F can read file contents, a string, or command output. You want command output, so the IN() clause should be enclosed in single quotes. The # symbol is used to suppress echoing of the SET command line.
for /f "delims=" %A in ('dateMath.bat %Date_Pattern% - 2') do #set "result=%A"
If you want to use the above command in a batch script, then the FOR variable percents need to be doubled. Your script probably has echo off, so # is not needed.
for /f "delims=" %%A in ('dateMath.bat %Date_Pattern% - 2') do set "result=%%A"
There is an entirely different approach you could take: modify your batch script to optionally store the result directly in the variable. You should read the following excellent tutorial from DosTips.com DOS Batch - Function Tutorial The site constantly refers to DOS, but in reality it is a site that specializes in all things dealing with Windows batch scripting.

updating command line parameters in batch file

**Batch file **I am writing batch file that takes in command line parameters and do some stuff if the parameters match. But when the run the batch file again with the new parameters, the file still runs with the old parameters.
first run : file.bat -name hello -w 400 -r 320
second run : file.bat -name hello -w 400.
When i do the second run of the file, it still performs the first run, i mean to say it still considers the parameters from the first run. Does anybody know why this is the case?
Thanks in advance.
Sorry for not posting the batch file code.
below mentioned is the code.
set filename=
set rate=
set hidden=
set rate=
:recheck
if "%1"=="-help" goto :help
if "%1"=="-name" goto :filename
if "%1"=="-h" goto :hidden
if "%1"=="-w" goto :weight
if "%1"=="-r" goto :rate
if "%~1"=="" goto :endofcommandline
:filename
shift
set filename =%1
shift
goto :recheck
For the other part of the file, I use the variable "filename" to do other stuff. I also use setlocal and endlocal at the beginning and the end of the file.
I have other corresponding labels for the each if statement and set different variables to the values passed to them if any by the user.
Sometimes, I also get echo is off when I try to print out the value of some variable.
All the variables which I use are cleared in the beginning of the file as mentioned above.
There are a couple points here.
"I also use setlocal and endlocal at the beginning and the end of the file."
"All the variables which I use are cleared in the beginning of the file as mentioned above."
Setlocal command does NOT clear the variables, it preserve current variables from posterior modification. This mean that if in a previous execution of your Batch file, or even via typed SET commands, filename variable was defined, it value remains until it is deleted or modified.
"Ok!", you said, "filename variable is modified the second time the Batch file run, Right?"
Well, no... The following line:
set filename =%1
does NOT modify "filename" variable, but "filename " instead (filename and a space). Try this:
set filename=No space
echo %filename%
set filename =Bad name with trailing space
echo %filename %
echo %filename%
You must carefully check your program to avoid this type of errors.

Multiple do commands in a for loop: Echoing a string to a file and then redirecting to the command window

I am trying to write a batch file to iteratively execute a fortran compiled executable. Normally one would go to the windows command prompt, type 'Model.exe'. This would bring up a dos command window asking the user to type a required file name directly in to the command window at the dos prompt.
I want to write a batch file that will do this bit for me, and also iterate this step so that I can run 10 simulations consecutively instead of having to do it by hand. This kind of shell operation would be straightforward in linux, but I do not have this available.
My pseudo code would look like this:
for /L %%run in (1,1,10) do
(set str=Sim%%run
echo.%str% > input.txt
Model.exe < input.txt)
You could break this down in to the following steps:
Assign variable 'run' a value. (e.g. 1)
Concatenate this with a string ("Sim") to make a new variable, "Sim1"
echo this to a text file ("input.txt")
Read the variable "Sim1" from file "input.txt"
Executable goes away and does its thing.
Repeat steps 1 -> 5, but with a new variable calle "Sim2" etc.
I can get the above to work if I use set str=Sim1 and then echo this directly to "input.txt", but I cannot get this to work as a loop. Am I missing something?
Best regards,
Ben
Ugh, cmd.exe's treatment of variable expansion is ugly. So, you need "delayed expansion", as follows:
setlocal enabledelayedexpansion
for /L %%i in (1,1,10) do (
set str=Sim%%i
echo !str! > input.txt
Model.exe < input.txt)
endlocal
(Of course in this particular case you could just say echo Sim%%i > input.txt but I assume there's a good reason why you want to go via another variable.)

Resources