Tuesday, October 11, 2011

Batch Files: Tips and Tricks

I spent a lot of time one weekend creating a utility I call AutoGCC. GCC is a compiler that comes with Cygwin for Windows. When running this compiler and finishing assignments there are a whole lot of very annoying commands and actions to complete, that are highly repetitive. Perfect situation for constructing a utility! Here is a link to the program, which I update as I find bugs or think of additional features: http://www.mediafire.com/?v3q5f4ntvceq4wa

There are a few tips and tricks I learned about batch programming that I'd like to share, and to document for my own future reference.


You can use parentheses to link multiple lines so they are treated as a single line. This allows you to make nicely formatted if statements, like so: 

if not exist %CD%\error_files\ (
mkdir %CD%\error_files\
)

The next trick that took me forever to understand the syntax of, is string manipulation. Take the variable %PATH% for example. It is a string. However what if I want to modify a portion of this string to my own liking? Look at the following: %PATH:;c:\AutoGCC=%

%PATH:;c:\folder=%

That code actually searches for a matching sequence of characters of the sequence ";c:\folder", and will set that portion of the string %PATH% to nothing. This is basically deleting an element from the %PATH% variable. You could also have done:

%PATH:;c:\folder=;c:\LOL%

Which would change the element ;c:\folder to ;c:\LOL.


There is also a nice way to edit the path (or any registry key) of a user's machine by editing the registry key for the system path! This will however require a restart to take effect. Here is the syntax I used in AutoGCC to modify my system's path (type reg add /? for information on the reg add command):

reg add "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v Path /t REG_EXPAND_SZ /d "%PATH:;c:\AutoGCC=%" /f

You can also use the CALL command to launch a specific portion of your code as if it were its own batch file. This is really useful for making functions within your batch file. Take a look at the following code:

if exist %file% (

  if %var% NEQ 2 (
    call FUNCTION_1
  )
)


:FUNCTION_1
  do stuff...
  ...
  ...
  goto EOF

The above code will go to the line labeled with FUNCTION_1 if %file% exists, and then return just below the goto FUNCTION_1 statement once the line goto EOF is reached. goto EOF sends the control to the end of the file, though since FUNCTION_1 was called by a call command, it is as if it is an emulated batch script of its own, and the emulation will close, not the original environment that called it.


These few things are extremely useful for me when working on my batch scripts, and hopefully will be for you as well!

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.