batch-file

A common batch file to setup variables


I am working on multiple batch files and I want them to share some variables, so I created a batch file that has all these setups SetupEnv:

rem General setup
:: To pause or not after running a batch file
SET isPause = true

:: The directory where your source code is located
SET directory = D

:: The folders where your primary & secondary source code is located
:: I like to have two source code folders, if you don't then just have them pointing to the same folder
SET primary_source_code = \Dev\App
SET secondary_source_code = \Dev\App2

:::::::::::::::::::::::::::::::::::::::::::: XAMPP :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
rem If you're using XAMPP then set these up
:: Your destination folder
SET base_destination = C:\xampp\htdocs

:: The base url that is pointing to your destination folder (in most cases it's localhost)
SET base_url = http://10.0.2.65

:::::::::::::::::::::::::::::::::::::::::: Angular :::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
rem If you're using angular set these up
:: The folder where you built code is copied
SET build_file = dist

And from another batch file I'm calling that file first:

::setup
call ../SetupEnv

echo %directory% dir
pause;

The problem is that even though the file runs smoothly and I can see in the outputs that things are being setup, the variables are not coming across to the file I'm calling it from. So in that example %directory% is not being printed.

EDIT I also tried using Joey's answer:

::setup
for /f "delims=" %%x in (../SetupEnv.txt) do (set "%%x")

echo %directory% dir
pause

But that didn't work either and %directory% didn't get printed


Solution

  • setting variables in a called batchfile works, as long as you don't use setlocal in the called batchfile (there will be an implicite endlocal, when it returns, so the variables would get lost):

    > type a.bat
    set var=old
    echo %var%
    call b.bat
    echo %var%
    
    > type b.bat
    set var=new
    
    > a.bat
    
    > set var=old
    
    > echo old
    old
    
    > call b.bat
    
    > set var=new
    
    > echo new
    new
    
    >
    

    for the alternative for solution, I would slightly change it to:

    for /f "delims=" %%a in ('type b.bat^|findstr /bic:"set "') do %%a
    

    This will only "execute" lines, that start with set (ignoring capitalization), so you can keep any comments inside that file.

    Note: ... do set "%%a" adds another set to the line (you have already one in the file), resulting in set "set var=value", which you obviously don't want.