Dr. Mark Humphrys

School of Computing. Dublin City University.

Online coding site: Ancient Brain

coders   JavaScript worlds

Search:

Free AI exercises


Windows batch files

You can write scripts ("batch files") on Windows command line.

To write a batch file

  1. Put commands in a file with a name like PROG.BAT
  2. From command line:
     notepad prog.bat 
  3. To run it type PROG

  4. Does it have to be in the PATH?
    • Windows will run progs found in dirs in the environment variable %path%
    • And it will run progs found in the current dir.
  

Script to get started


@echo off
rem the above line prevents the script echoing back the commands
rem is a comment

dir




Some features

  1. Pipes:
     dir | find "string" | sort
    
    Example:
    Go into henryiv_1
    find "Scot" act*.html
    find "Scot" act*.html | find "Scots"
    find "Scot" act*.html | find /v "Scots"
    
    

  2. Redirection:
     dir > file
    

  3. Environment variables:
    
    set myvar=string
    echo myvar is %myvar%  
    
      echo path is %path%
    
      copy %1 %homepath%\backup
    
    

  

Flow of control statements

  1. IF and command-line arguments and string compare:
    
    if '%1'=='' echo no arg  
    
    if '%1'=='' ( echo no arg ) else ( echo arg )
    
    

  2. FOR loops and CALL of another batch file:
      for %%i in (*.html) do call secondprog %%i
    

  3. multiple statements in block:
    
    for %%i in (*.*) do (
      echo %%i
      dir %%i
    )
    
    
  4. IF EXIST
    
    IF EXIST "C:\Program Files\Mozilla Firefox" (
      echo Firefox exists
    ) ELSE (
      echo Firefox missing
    )
    
    
    Cannot change this layout around too much.

  5. We can get around the lack of directory wildcards with a FOR loop:
    @echo off
    for /d %%d in ("r*") do find "Ireland" %%d\*html
    
    This is the equivalent of:
    grep Ireland r*/*html  
    


Misc

  1. exit /b
    exit the script
    (with no argument it will close the cmd window)




The BAT scripting language is generally simpler than UNIX/Linux Shell, and the standard utilities are fewer, and have less options, than on UNIX/Linux.

But there are more powerful Windows command-lines.



ancientbrain.com      w2mind.org      humphrysfamilytree.com

On the Internet since 1987.      New 250 G VPS server.

Note: Links on this site to user-generated content like Wikipedia are highlighted in red as possibly unreliable. My view is that such links are highly useful but flawed.