0

I need to call a batch file with a command I want it to execute. This command contains the %cd% pseudo-variable, which expands to the current directory. Say, I want to run test "echo %cd%". The problem is that %cd% expands before test is called.

Normally, you can escape a variable by doubling the percent signs, but this does not seem to apply to pseudo-variables. For instance, echo %%ProgramFiles%% will print %ProgramFiles%, but echo %%errorlevel%% will print %0%. What do I do?

2 Answers 2

1

The general-purpose escape character in Windows Command Prompt — the analog of \ in the rest of the universe — is caret (^).  Try “^%cd^%”.

(Edit)

… and then,

echo %1 > temp.bat
call temp.bat
del temp.bat

Yes, it’s terribly ugly, and there really ought to be a better way.  Well, I can’t find it.

2
  • Ah, but now test "echo ^%cd^%" prints %cd% instead of the current directory. What I need is for the pseudo-variable to be preserved when I pass it to the script, but expanded inside.
    – Don Reba
    Dec 4, 2012 at 1:27
  • OK, I’ve edited my answer to address that problem. Dec 4, 2012 at 3:18
0

I'm not having much luck without getting CALL involved, either. With this test.bat:

@%*

invoking test.bat call echo ^%cd^% works as expected. Or, putting the CALL inside test.bat:

@CALL %*

and invoking test.bat echo ^%cd^% works. (This is safer anyhow, since if test.bat is getting called from another script, then passing a script to it won't run the risk of exiting prematurely.)

I suppose which works better for you (or if either can be made to work at all) depends on the specifics of your scenario.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.