Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running a non bat extension file as a batch file

Let's say I have a text file, it contains batch commands. How can I run that text file as a batch file from within one, without renaming it. I want too keep a portable aspect too it, so no registry keys or such.

The reason for no renaming is too prevent leftover unrenamed files upon unexpected closure.

like image 220
Jared Allard Avatar asked Oct 21 '25 06:10

Jared Allard


1 Answers

The simplest way is this:

cmd < file.txt

As in the previous answers, there are several commands that will not work in this file, like GOTO, SETLOCAL and others. However, multiline nested if and for commands do work as long as for replaceable parameters use just one percent (like in the command-line).

Although this method alaways show in the screen the executed commands (@echo off not works here), you may redirect the output to NUL and in the "Batch" file redirect the desired output to CON. For example, this is test.txt:

@echo off
echo Hello World! > CON

(for /L %a in (1,1,10) do (
   echo Turn: %a
   if %a equ 4 echo TURN NUMBER FOUR!
)) > CON

Output example:

C:\> cmd < test.txt > NUL
Hello World!
Turn: 1
Turn: 2
Turn: 3
Turn: 4
TURN NUMBER FOUR!
Turn: 5
Turn: 6
Turn: 7
Turn: 8
Turn: 9
Turn: 10
like image 82
Aacini Avatar answered Oct 23 '25 13:10

Aacini