Ravindra Sinare
Ravindra Sinare

Reputation: 675

How I can run commands using batch and save the output in text file?

I am running some commands and getting the output. Now I want make it automatic. I have created the .bat file but I am unable to save output.

How can save the output after successfully running the command in batch file.

Upvotes: 1

Views: 14842

Answers (3)

paulsm4
paulsm4

Reputation: 121649

Two choices:

  1. Redirect (">") your commands in the .bat file directly, as you invoke them

EXAMPLE:

echo %DATE% %TIME% > mylog.txt
cmd1 >> mylog.txt
cmd2 >> mylog.txt
...
  1. Create a 2nd .bat file to call the first, and redirect everything in the first one:

EXAMPLE

call mybatfile.bat > mylog.txt
  1. Side notes:

    a. "Text output" actually consists of two, separate "streams": stdout (normal text), and stderr (error text). If you want to redirect both to the same log file, you can use this syntax:

    call mybatfile.bat > mylog.txt 2>&1

    b. ">" erases the previous contents before writing. ">>" appends the new output to the previous contents of the file.

Upvotes: 2

foxidrive
foxidrive

Reputation: 41234

Using code from the answer from @paulsm4:

This method is better than adding a space at the end of each line as there are no extra and unwanted characters.

 > mylog.txt echo %DATE% %TIME%
>> mylog.txt cmd1
>> mylog.txt cmd2

The reason why spaces are used in this method is because some numerals get eaten when there is no space.

echo %DATE% %TIME% > mylog.txt
cmd1 >> mylog.txt
cmd2 >> mylog.txt

Upvotes: 0

fjellfly
fjellfly

Reputation: 388

Just add a "> filename" after the command you are calling your script and the output will be written into this file ("filename").

See https://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/redirection.mspx?mfr=true for more details (appending, ...).

Upvotes: 1

Related Questions