0

How can I copy a file inside a bat file using a set variable.

[run.bat]

set MY_WORKSPACE=workspace1.0.1
copy /Y /V D:\%MY_WORKSPACE%\webapp\target\app-generic.war C:\Opt\jboss-4.2.3.GA\server\default\deploy\

In above example, %MY_WORKSPACE% is invalid, however I can see the value by using 'echo'

2
  • Your syntax is absolutely correct. Both the "set", as well as the "%MY_WORKSPACE%". Q: Do you actually have a directory "d:\workspace1.0.1"? Q: What is the exact error you're getting? Commented Apr 18, 2012 at 7:24
  • 1
    Like Joey asked: Q: Is that the whole batch file you're showing us? Commented Apr 18, 2012 at 16:03

2 Answers 2

3

Is that the whole batch file you're showing us?

I have a vague feeling you're doing the set and copy inside an if or similar statement with a block, e.g.

if foo==bar (
  set MY_WORKSPACE=workspace1.0.1
  copy ...
)

In this case you need delayed expansion for the variable change to take effect because the block in parentheses is parsed as a single command and all variables are substituted at parse time, not when runnin a command. Therefore %MY_WORKSPACE% will be empty once the block runs.

You can solve this by using

setlocal enabledelayedexpansion

at the top of your batch file and using !MY_WORKSPACE! instead of %MY_WORKSPACE% which will expand the variable just prior to running the command, not while parsing.

Sign up to request clarification or add additional context in comments.

4 Comments

+1 I believe it is more than a "vague" feeling, considering this is one of the most common root causes of problems that people have with batch files :-)
It's almost always the answer to »I'm setting the variable but the value doesn't get picked up by the line after it« ;-)
Thanks Joey... that setlocal fixed the problem. you were right it was inside the if-block
Mwahaha! Once again my psychic powers save the day!
0

Try this way:

set MY_WORKSPACE="workspace1.0.1"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.