Can variables created in one batch file be used in another?
I have some batch files I'm trying to organize better, generally trying to get it to a spot where they might be able to be worked on a little easier by someone who comes down the road eventually.
In doing this it occurs to me that I don't know if batch scripting will persist variables in memory. Here's a example of what I have:
SET SQLSERVER="TestServer1" SET SQLTEXT="select * from some_table" IF NOT %SQLSERVER% = "" CALL RUNSQL.BAT END IF
In RUNSQL.BAT I have something similar to this:
SET SQLCMD="C:\Program Files\Microsoft SQL Server\100\Tools\Binn\SQLCMD.EXE" %SQLCMD% -S %SQLSERVER% -Q %SQLTEXT" EXIT
My question is: Will the variables set in that first bit of text persist into RUNSQL.BAT?
Environment variables are stored inside a block of memory in the memory space of each process. Each time a process is started, the child process gets a copy of the environment of the parent process, so at the time of start both see the same data, but don't share the same variables, child has a COPY. Any change in the environment of the parent is not seen in the environment of the child. Any change in the environment of the child is not seen in the environment of the parent.
In batch files, if both scripts are running inside the same cmd instance, both share THE SAME VARIABLES, those in the environment memory of the cmd.exe process that is running both batch files.
In the posted sample code, cmd.exe is running the first batch script, and it, inside the same cmd, calls the second batch script, that is running inside the same cmd instance, so, both are sharing the same environment variables. Second batch sees the same variables and any change made in second batch is seen in first on return of the call.