Tuesday, August 3, 2010

Running Cygwin in Your Current Directory

Most of the time I'm on the command line, I'm using the Windows command prompt. When I need a Bash shell (cygwin), it's really annoying to have to cd all the way back to the directory I was in before calling cygwin.

After locating Martin Gramatke's email to the Cygwin mailing list (Thanks Martin!), I put together an updated cygwin.bat, and .bash_profile in order to let Cygwin remember my working directory.

The first part is a modified cygwin.bat file. I've added c:\cygwin\bin to my PATH variable already, so it is no longer necessary to cd to the c:\cygwin\bin directory just to invoke bash. The below cygwin.bat file no longer changes directories on you, and also stores your current working directory in an environment variable so bash can tell if/where you would like to pick up working once bash has started.

@echo off
setlocal

for /f "usebackq delims=" %%i in (`cygpath "%cd%"`) do set BASHHERE=%%i

bash -li %*

endlocal
Note the handy 'for-piping' of the cygpath command into the BASHHERE variable.

The second part of the process involves telling bash to switch to your 'preferred' directory when your profile is loaded. Adding the following lines to the end of your .bash_profile (~/.bash_profile) will instruct bash to cd to the directory stored in the updated cygwin.bat script so you can seamlessly resume working in the same directory - using Cygwin!
if [ "$BASHHERE" != "" ]; then
cd "$BASHHERE"
fi
I normally put this at the end of the file.

Using both of these changes will mean that whenever you run cygwin using the cygwin.bat script, your currrent working directory will be preserved. If you wish to start bash in your home directory, don't make the call to cygwin.bat, and simply call bash.exe directly (with any options you may want)

Cheers!

No comments:

Post a Comment