views:

792

answers:

4
cd ../../jobs
set CLASSPATH=.;../xyz.jar;../mysql-connector-java-5.1.6-bin.jar
java folser.folder1 ../Files/MySQL.xml
cd ..

I need to run the batch file from any directory. I have set the paths for java. Can anybody help me?

A: 

You message was a bit garbled, I'm assuming you're saying that java is on the path but you can't properly run your application from a batch file. It looks like you are missing the classpath option (-cp) for java. Try this:

cd ../../jobs
set CLASSPATH=.;../xyz.jar;../mysql-connector-java-5.1.6-bin.jar
java -cp %CLASSPATH% folser.folder1 ../Files/MySQL.xml
cd ..
jdigital
This does not answer the poster's question
vladr
Do you need "-cp"? I though Java picked it up automagically from CLASSPATH (although you may need to export rather than just set).
paxdiablo
A: 
Richard Nichols
%cd% is not the batch file's directory, it is the current directory, e.g. I'm in C:\, I invoke C:\test\batch.bat; %cd% is C:\, not C:\test.
vladr
@Richard - %~dp0 would get the batch file directory
McDowell
+2  A: 

Under *nix (e.g. Linux):

cd "`dirname \"$0\"`"
# your current directoy is now the script's directory
cd ../../jobs
set CLASSPATH=.:../xyz.jar:../mysql-connector-java-5.1.6-bin.jar
java folder.folder1 ../Files/MySQL.xml
cd ..
# when the script terminates, you are automatically
#  back to the original directory

Under Windows NT/XP/etc.:

SETLOCAL
PUSHD .
REM current directory has been saved and environment is protected
CD /d %~dp0
REM your current directoy is now the script's directory
CD ..\..\jobs
SET CLASSPATH=.;..\xyz.jar;..\mysql-connector-java-5.1.6-bin.jar
java folder.folder1 ..\Files\MySQL.xml
CD ..
REM before the script terminates, you must explicitly
REM return back to the original directory
POPD
ENDLOCAL

Cheers, V.

vladr
I don't think you're back in the original directory at the end for the Windows version. You should use setlocal/endlocal to ensure environment changes don't leak out of the script - you may also need to store the current path and drive and restore when finished.
paxdiablo
Good point. Updated accordingly. Good ole' MS implementation...
vladr
And +1. Well, stuff me! I didn't even know about pushd/popd, I've been saving my PWD in an environment variable. Must remember to change that code next time it's checked out.
paxdiablo
A: 

Although I can't comment on Vlad's answer (comments require more points than answers?!) I would always be wary of relying on:

CD /d %~dp0

because Windows can't CD to UNC paths and has a nasty habit of dropping you into %windir% instead with potentially catastrophic results.

Instead, although it is more long-winded, you are usually better off referring to %~dp0 (or a variable containing that value) each time you need a full path.

BAD:

cd /d %~dp0
rd temp

GOOD:

rd %~dp0\temp
sahmeepee