user48094
user48094

Reputation: 10641

how to run the batch file from any folder

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?

Upvotes: 2

Views: 3653

Answers (4)

vladr
vladr

Reputation: 66721

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

Upvotes: 3

sahmeepee
sahmeepee

Reputation: 532

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

Upvotes: 1

Richard Nichols
Richard Nichols

Reputation: 1940

Use %cd% to get the current directory (i.e. the one that the batch file lives in)

e.g.

set JAVA_HOME=%cd%\jdk1.x.x
set PATH=%JAVA_HOME%\bin;%PATH%
set CLASSPATH=%JAVA_HOME%\lib\tools.jar;%cd%\lib\myjar.jar;etc,etc

Upvotes: 0

jdigital
jdigital

Reputation: 12296

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 ..

Upvotes: 0

Related Questions