Wednesday, November 9, 2011

How to set up a .rc file for the cmd shell on windows

In the Unix world, all command shells allow you to set up your command line environment by adding commands to 'rc' files, .bashrc, .profile, .tcshrc, .cshrc, etc... The cmd.exe shell on Windows does not have a '.cmdrc' file, so you are left with a default setup every time you start a new shell. Luckily, there is a way to source a batch file when cmd.exe starts.


Here's a section of the help text from running “cmd /?”:
If /D was NOT specified on the command line, then when CMD.EXE starts, it looks for the following REG_SZ/REG_EXPAND_SZ registry variables, and if either or both are present, they are executed first.

HKEY_LOCAL_MACHINE\Software\Microsoft\Command Processor\AutoRun

and/or

HKEY_CURRENT_USER\Software\Microsoft\Command Processor\AutoRun

So, you can set up your system to run any script every time you run cmd.exe. Just run regedit, navigate to the path above, create the string value, and set it to the path of a batch file, excluding the '.bat' extension.

For example, “c:/rc”, where the actual file is c:/rc.bat. Batch files are run the way scripts are sourced in Unix shells, so all variables and changes to the environment will affect the new shell.

1 comment:

Dan edens said...

Here is something you can drop in a file.reg and run to import!

(NOTE: The path is for my machine, you may have the other path method above, CHECK FIRST ;)

> cat autoruns.reg
Windows Registry Editor Version 5.00

[HKEY_CURRENT_USER\SOFTWARE\Microsoft\Command Processor]
"Autorun"="%sourcefile%"



My personal definition for %sourcefile%:

> echo %sourcefile%
C:\Users\Dan.Edens\bin\.rc.cmd


And my .rc.cmd looks like this!

@echo off
@REM autorun.reg

@REM Windows Registry Editor Version 5.00

@REM [HKEY_CURRENT_USER\Software\Microsoft\Command Processor]
@REM "Autorun"="%sourcefile%"

@REM setx sourcefile %userprofile%/.rc.cmd


@echo OFF

IF /I "%macrosloaded%" EQU "1" (
set _tail=%*
call set _tail=%%_tail:*%1 =%%
IF "%~1" == "" (
goto:eof
) ELSE IF "%~1" == "add" (
goto:add
) ELSE IF "%~1" == "grep" (
GOTO:grep
) ELSE IF "%~1" == "edit" (
GOTO:vim
)
) ELSE (
goto:load
)

:add
echo "%_tail%" appended to doskey.
echo This method is subject to delimitor conflicts
echo "%_tail%" >> "%userprofile%/.doskey"
goto:eof

:grep
doskey /macros:all|grep -i %_tail%
goto:eof


:edit
vim "%userprofile$/.rc.cmd"
goto:eof


:load
Doskey /macrofile="%userprofile%\.doskey"
set macrosloaded=1
goto:eof