I have a windows cmd batch file that uses a variable, but everywhere that variable is used after setting it is failing.
Here is my batch script:
@echo off
if exist Transactions.csv (
set datestr=%date:~10,4%%date:~7,2%%date:~4,2%%time:~0,2%%time:~3,2%%time:~6,2%
rename Transactions.csv Transactions-%datestr%.csv
curl -s -o curl.log --form upload=@Transactions-%datestr%.csv http://192.168.5.217/test_upload.php
set datestr=
)
The file gets renamed to “Transactions-.csv”, and the curl command works OK because it’s sending the file as is, but I’d like it to properly rename the file.
If I comment out the echo off line, this is what I get back:
if exist Transactions.csv (
set datestr=20112206112720
rename Transactions.csv Transactions-.csv
curl -s -o curl.log --form upload=@Transactions-.csv http://192.168.5.217/test_upload.php
set datestr=
)
Note the missing areas where %datestr% should be.
Any ideas why these variables are not properly being parsed?
When you have a block of commands enclosed in parentheses, the entire block is parsed before its first command executes. That means, all the
%var%expressions inside that block are replaced with their values at that time. That’s why you could see nothing in place of%datestr%when you ran the script with@echo offcommented out.So your decision to move the body of the IF statement outside the brackets was right.
Another solution to that would be to use delayed expansion:
As you can see, the delayed expansion mode is introduced with the
setlocal EnableDelayedExpansioncommand. Note also the change of syntax:!instead of%denote the delayed expansion of the corresponding variable/expression. When delayed expansion is enabled, you can still use%for immediate expansion, where appropriate.