Batch Files

Submitted by Karthik on

Batch files:-

Batch files are a set of dos commands stored in a file and executed top to bottom. The commands written in a batch  file will be executed on at a time by the sequence we had written the commands.

Example:

@echo off
echo Hello Welcome to DOS Programming
pause

Save the above code in hello.bat, then type hello.bat to run the batch file. 

Special commands used in batch file:-

echo:-

    This command is used to display any given test as a message. @echo off used to hide the commands in out put.

pause:-
    
    When we give this command it prompts the message "press any key to continue..." and waits for a keystroke.


Eg.1:-
Type the following in command prompt, demo1.bat file will be created.

    c:\>copy con demo1.bat

    @echo off
    echo
    echo    Hello world!
    echo
    ^z
        1 file(s) copied


Now run the batch file.

   c:\>demo1.bat
Output:-
                      Hello world!

call:-

    To call  any batch file for execution within the current batch file.

Eg.2:- (demo2.bat calls demo1.bat)

@echo off
dir
call demo1.bat
echo demo1 batch file was executed sucessfully.



IF ERROR LEVEL:-

    The error level statement is used to re-direct the control to someother label.

E.g.3:-
              
@echo off
:start
cls
echo*******************
echo 1.Display all the files
echo 2.Display files in lowercase
echo 3.Display date
echo 4.Display time
echo 5.Exit
echo***********************
choice/c:12345 "enter your choice"
if errorlevel 5 goto end
if errorlevel 4 goto d
if errorlevel 3 goto c
if errorlevel 2 goto b
if error leve l  goto a
:a
dir
pause
goto start

:b
dir/l
pause
goto start

:c
date
pause
goto start

:d
time
pause
goto start

:end