BATCH SCRIPTING FOR NOOBS

Created by King Cobra using ©LogicOpsLabs Course and Github Repository
View my GitHub, https://www.github.com/pushpesssh/

Click here to access example codes and PPTX.

BATCH [.bat] SCRIPT BASICS

        echo                                       Print something
        echo.                                      Print a blank line
        @echo off                                  Start scripts with this
        pause                                      End scripts with this
        cls                                        Clear the Screen
        echo %var%                                 Print the variable
        arp -a >> [file path]                      Append the results in file
        start                                      start a file or application
        rem                                        Comment
        copy                                       Copy
        del                                        Delete
        title                                      Title of the Window
        mkdir/rmdir                                Make or remove directories
        setlocal EnableDelayedExpansion            Allows to use !var!
        title                                      Set the title of the Window
        exit                                       Just exit
        goto label                                 Trigger commands in :label
        :label                                     List Commands triggered when goto executes
        set /p                                     Promtp user
        if /i !var!                                Remove case-sensitivity

         

STARTING FORMAT


        @echo off
        setlocal EnableDelayedExpansion
        title ...
        color f
        cls

        _

        :funcexit
        echo.
        set /p opt=Type 'YES' to exit command prompt:
				if /i \"!opt:~0,1!\"==\"Y\" (
				        exit
				) else if /i \"!opt:~0,1!\" NEQ \"Y\" (
				        exit /b
				)
  

ALL COMMANDS

Click here to access all Command List of Command-Prompt.

OPERATORS IN BATCH

1. Arithmetic Operators (used in SET /A)

        +     Addition                   set /a x=5+2
        -     Subtraction                set /a x=5-2
        *     Multiplication             set /a x=5*2
        /     Division (int only)        set /a x=5/2 → 2
        %     Modulo (remainder)         set /a x=5%%2 → 1
        &     Bitwise AND                set /a x=5&3
        |     Bitwise OR                 set /a x=5|2
        ^     Bitwise XOR                set /a x=5^3
        <<    Bitwise shift left         set /a x=1<<3 → 8
        >>    Bitwise shift right        set /a x=8>>2 → 2
        ~     Bitwise NOT                set /a x=~5
        ()    Grouping                   set /a x=(5+3)*2

2. Logical/Comparison Operators (used in IF)


        ==      Equal to                 if "%x%"=="test" ...
        NEQ     Not equal to             if %x% NEQ 5 ...
        LSS     Less than                if %x% LSS 5 ...
        LEQ     Less or equal            if %x% LEQ 5 ...
        GTR     Greater than             if %x% GTR 5 ...
        GEQ     Greater or equal         if %x% GEQ 5 ...
        NOT     Logical NOT              if NOT "%x%"=="test" ...
        !var!   Delayed expansion        Used with setlocal enabledelayedexpansion

Symbols can be used in place of Keywords

3. Redirection Operators


        >       Redirect output (overwrite)             echo Hello > file.txt
        >>      Redirect output (append)                echo Hello >> file.txt
        <       Redirect input from file                sort < file.txt
        2>      Redirect std. error messages/stderr     command 2> error.log
        1>      Redirect std. output/stdout             command 1> out.log
        2>&1    Merge stderr into stdout                command > all.log 2>&1
        nul     Send output to null                     command > nul 2>&1

4. Control Characters / Flow Operators


        &     Command AND           echo A & echo B
        &&    Conditional AND       dir && echo success
        ||    Conditional OR        dir abc || echo failed
        ()    Grouping              if exist file (echo yes)
        ^     Escape character      echo 2^>nul
        |     Pipe                  dir | find "log"

5. FOR Loop Variables


        %i      Command line only             for %i in (*) do echo %i
        %%i     Batch scripts                 for %%i in (*) do echo %%i
        %%~nxF  Name + extension of file      for %%F in (*) do echo %%~nxF

6. FOR Variable Modifiers


        %%~fA  Full path
        %%~dA  Drive letter
        %%~pA  Path only
        %%~nA  Filename only
        %%~xA  Extension only
        %%~sA  Short 8.3 name
        %%~aA  Attributes
        %%~tA  Modified time
        %%~zA  File size

7. Environment Variables


      %cd%        Current directory
      %~dp0       Script directory
      %random%    Random number
      %errorlevel% Last exit code
      %time%, %date% Time and date

8. Real-World Script Example

@echo off
      setlocal enabledelayedexpansion

      set /a x=5
      for %%i in (1 2 3) do (
        set /a x=!x!+%%i
        echo !x!
      )

      if exist result.txt (
        del result.txt && echo Deleted old result
      ) || (
        echo No file to delete
      )

      dir *.txt > list.txt 2> nul

9. Common Pitfalls


    - Using %var% inside () blocks without delayed expansion
    - Forgetting %% for FOR in scripts
    - Using == instead of EQU inside SET /A
    - Not escaping ^, |, & inside echo

SETLOCAL: EnableDelayedExpansion

By default, variables inside parentheses are expanded only once at parse time. Enabling delayed expansion allows you to use `!var!` to get the current value during execution.

GOTO vs CALL

Command Purpose Behavior
goto :label Jumps to a label 🚫 No return — like a hard jump
call :label Calls a label/function ✅ Returns after goto :eof

MANIPULATING OF STRINGS

1. Referencing Arguments of a:function


        call :function "!var!" "!var1!"

        :function
        echo %1
        echo %~2
      

The above code echo the var and var1. Both are 1st and 2nd Argument of :function.

They can be reffered to as %1 and %2

%~2 is used to remove quotes in output

Changing Values


        set str=HelloHell
        echo str
        set str=!str:~0,5!
        echo str
      

The above code makes the String "HelloHell" to "Hello". ~0,5 means from 0 to 5

This is called Left String


        set str=!str:~-4!
      

~-4 means Right string aka Value from Backwards. It gives Hell as Result


Now, The mid-string


        set str=!str:~4,6!
        echo str
      

This means Starting from 4 and taking upto 6. Indexing starts from 0 in all languages.

Result will be : loh, from 4th character to the 6th character.

Removing Spaces from a string


        set /p str=Enter a string:
      

User might enter spaces. so we must remove through this:


        set str=!str: =!
      

This command says " " = Nothing, as it end there.
It can also be utilized to remove some part of the string to get some wanted part.

ARRAYS AND LOOPING

Defining Arrays

We ain't got any defined ARRAYSs in BATCH. But we can simulate them using variables. For example,


        set item[0]=apple
        set item[1]=banana
        set item[2]=cherry
  

Looping through Arrays


        @echo off
        setlocal enabledelayedexpansion

        set item[0]=apple
        set item[1]=banana
        set item[2]=cherry
        set count=2

        for /L %%i in (0,1,%count%) do (
            echo !item[%%i]!
        )
  

FOR

Starts a loop construct.

/L parameter

Loop through a range of numbers. The syntax of sequence is (start, step, end).

%%i

Loop variable. In batch files, use double percent signs (%%) while in Shell use (%). It is the iterating variable name which will become the value when provided. Use as a variable inside of loop to iterate every given value of sequence.

DO (...)

DO is just DO. It does everything you do in DO.

!item[%%i]!

This is where the *array magic* happens. You’re telling CMD: 1. Substitute the current numeric index (like `0`, `1`, `2`) into the variable name `item[%%i]`.
2. Then expand it (with delayed expansion, using `! !`) to retrieve its stored value. So, iteration by iteration:


        i = 0 → !item[0]! → apple
        i = 1 → !item[1]! → banana
        i = 2 → !item[2]! → cherry
  

Managing Array Count

CMD doesn't know what array is and also you need to manually track the length.


        set item.array.count = 3
        rem Index starts from 0 in scripting languages.
  

If you wanna add other do this:


        set item[%count%]=date
        set /a array.item.count+=1
  

It will increment the count while adding the new Array index.

Common Parameters for Scripting


        /I for Ignore case-sensitivity  [FOR CONDITIONAL LOOPS]
        /L for Loop Sequence: numeric
        /F for Loop Sequence: token/text
        No Switch for Loop Sequence: files
        /D for Loop Sequence: Folder/Directories
  

When you use `/L`, the parentheses `(start,step,end)` define the sequence parameters:

Parameter Meaning Example
start The first number in the sequence 0
step How much to increment (or decrement) each iteration 1
end The number to stop at (inclusive) %count%

So the loop:
for /L %%i in (0,1,5) do echo %%i
Means:


        > Start at 0, increase by 1 each time, stop once you hit 5.
        > → outputs `0 1 2 3 4 5`
        

If You Need Non-Sequential Iteration

You have to use a different type of for — the /F loop.

Example: loop through a predefined list of arbitrary items:


for %%x in (0 2 4 7 9) do echo %%x

That’s a plain for, no /L — meaning it iterates over words separated by spaces.

Output:


0
2
4
7
9

So:

Switch Purpose Type
/L Numeric sequence start, step, end
(no switch) Explicit list of values manual entries

FOR - /X SWITCH