It seems that since I use SET to declare my variables in batch script, if I run it multiple times in cmd, the variable value will persist unless I explicitly reset them.
Do I have to use setlocal and endlocal to make sure the variables from one run doesn't persist over to another, without shutting down the CMD?
Yes, you should use SETLOCAL. That will localize any changes such that the old environment will be restored once ENDLOCAL is issued.
When all script processing finishes and you are returned to a command line context, there is an implicit ENDLOCAL issued for every active SETLOCAL. There is no need to explicitly issue ENDLOCAL.
Also, if your script (or routine) is CALLed, then when the CALL completes there is an implicit ENDLOCAL for every active SETLOCAL that was issued within the CALLed routine. No need to put ENDLOCAL at end of a routine, (though it doesn't hurt)
For example
output:
ENDLOCAL within a CALLed routine will never rollback a SETLOCAL that was issued before the CALL. For example.
Result: