user2506293
user2506293

Reputation: 865

Reading and writing integers to a text file with batch script

I have the following batch script:

@echo off
if exist test.txt (
    set /p foo=<test.txt
    echo "read: %foo%"
    set /A foo=foo+1
    (echo %foo%)>test.txt
    echo "wrote: %foo%"
) else (
    (echo 1)>test.txt
)

I expect the script to check for the existence of the file test.txt. If the file does not exist, the script should write 1 to the file. If the file does exist, the script should read the value from the file, increment it by one, and then write back the incremented file.

I would expect my output to thus look something like this:

C:\opt>test.bat

C:\opt>test.bat
"read: 1"
"wrote: 2"

C:\opt>test.bat
"read: 2"
"wrote: 3"

C:\opt>test.bat
"read: 3"
"wrote: 4"

However instead I get the following output:

C:\opt>test.bat

C:\opt>test.bat
"read: 2"
"wrote: 2"

C:\opt>test.bat
"read: 2"
"wrote: 2"

C:\opt>test.bat
"read: 3"
"wrote: 3"

C:\opt>test.bat
"read: 3"
"wrote: 3"

C:\opt>test.bat
"read: 4"
"wrote: 4"

C:\opt>test.bat
"read: 4"
"wrote: 4"

Why does the variable foo not appear to increment as expected?

Upvotes: 0

Views: 2658

Answers (2)

Squashman
Squashman

Reputation: 14290

Your code can be simplified.

If you set the variable to zero first and then read the text file with SET /P and redirection, it will overwrite the variable. At which time you can add 1 to it regardless of what state the variable is in.

@echo off
set "foo=0"
IF exist "test.txt" set /p foo=<test.txt
echo read: %foo%
set /A "foo+=1"
echo wrote: %foo%
>test.txt echo %foo%

You can even get rid of the IF EXIST and just redirect the error to nul when the file does not exist.

@echo off
set "foo=0"
(set /p foo=<test.txt)2>nul
echo read: %foo%
set /A "foo+=1"
echo wrote: %foo%
>test.txt echo %foo%

Upvotes: 1

Andreas
Andreas

Reputation: 5599

You need to use delayed variable expansion so that you get the current values from the calculation:

@echo off
setlocal enabledelayedexpansion
if exist test.txt (
    set /p foo=<test.txt
    echo "read: !foo!"
    set /A foo=foo+1
    (echo !foo!)>test.txt
    echo "wrote: !foo!"
) else (
    (echo 1)>test.txt
)

Upvotes: 3

Related Questions