Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Windows Batch File popd not working as expected

I am using the following batch script to run a Java Command Line tool.

@echo off
pushd %~dp0
setLocal EnableDelayedExpansion
set CLASSPATH="
for /R ./libs %%a in (*.jar) do (
    set CLASSPATH=!CLASSPATH!;%%a
)
set CLASSPATH=!CLASSPATH!"
java -cp !CLASSPATH! com.example.CLIApplication %*
popd

I have added the tool's directory to the System Variables PATH so that I can run it from any directory via the command prompt. This is working but the problem I am seeing is:

The tool's dir is C:\tool\ The user is in C:\ After executing the batch file the user is left in C:\tool\ not C:\

popd is getting called but the console navigates back to C:\too\ instead of staying in C:\

How do I ensure they users directory is not changed after the script finishes?

like image 421
lucasweb Avatar asked Sep 07 '25 00:09

lucasweb


2 Answers

The setlocal without endlocal causes this problem here.

You only need to add an endlocal just before calling popd.

In your code the popd returns to your first directory, but as setlocal stores all variables and all open setlocals are closed by implicit endlocals when the batch is exited, it will also restore the cd variable.

like image 131
jeb Avatar answered Sep 10 '25 06:09

jeb


I may be off track, but why aren't you using:

pushd .
like image 30
Derek Avatar answered Sep 10 '25 07:09

Derek