What is Batch File?
- A batch file is a text file containing a sequence of commands that are executed in the Command Prompt (CMD) in Windows.
- Batch files are saved with the
.bat
extension. - They automate repetitive tasks by executing multiple commands in a specific sequence.
- They can be used to perform a variety of tasks like file management, automation, system configuration, and more.
How a Batch File Works?
- Execution: When you run a batch file, each line of the file is processed and executed one by one in sequence.
- Batch Script: You can create a batch script by simply writing DOS/Windows commands in a text file, then saving the file with a
.bat
extension. - Automation: They are useful for automating tasks such as launching programs, copying files, making backups, or performing system maintenance.
Example of a Simple Batch File:
- Let's say you want to create a batch file that displays a message.
1. Open Notepad.
2. Type the following commands:
@echo off
echo Hello, This is an example of Batch File!
dir
pause
3. Save the file as sample.bat
4. Double-click the file to execute it.
- Explanation:
@echo off
: Hides the commands being executed, only shows the output.echo
: Prints a message on the screen.dir
: Lists all files in the current directory.pause
: Waits for the user to press a key before proceeding.
Basic Commands Used in Batch Files:
1. @echo:
- Controls whether commands are displayed during execution.
- Example:
@echo off
echo This will be displayed, but not the command itself.
2. echo:
- Displays messages or turns command echoing on or off.
- Syntax: echo [message]
- Example:
echo Hello, this is a batch file.
3. PAUSE:
- Pauses the execution of the batch file and displays the message "Press any key to continue…".
- Example:
pause
4. REM:
- Adds a comment in the batch file. Comments are not executed.
- Example:
rem This is a comment, it will be ignored by the batch file.
5. IF:
- Performs conditional processing in the batch file.
- Syntax: if [condition] [command]
- Example:
if exist "C:\file.txt" echo File exists
6. SET:
- Creates, modifies, or displays environment variables.
- Syntax: set variable=value
- Example:
set name=John
echo %name%
7. CALL:
- Calls another batch file from within a batch file.
- Syntax: call [batch file]
- Example:
call sample.bat
Program : Create a batch file to identify given number is ODD or EVEN.
In Notepad:
@echo off
set /p num1=Enter your value :
set /a ans=num1 %% 2
if %ans%==0 (echo The Number %num1% is Even) else (echo The Number %num1% is Odd)
pause
Output:
Comments
Post a Comment