Is there an equivalent source command in Windows CMD as in bash or tcsh?

爱⌒轻易说出口 提交于 2019-11-27 07:48:30

I am afraid not, but you can start using Powershell, which does support dot sourcing. Since powershell window is really based on cmd so all your dos command will continue to work, and you gain new power, much more power.

In the usual Windows command prompt (i.e. cmd.exe), just using call mybat.bat did what I wanted. I got all the environment variables it had set.

The dos shell will support .bat files containing just assignments to variables that, when executed, will create the variables in the current environment.

  c:> type EnvSetTest.bat
  set TESTXYZ=XYZ

  c:> .\EnvSetTest.bat

  c:> set | find "TESTX"
  TESTXYZ=XYZ
  c:>

IHTH.

Following example will help you to solve your problem.

env.bat This file is for setting variables. Its contents are given blow.

set name="test3"

test.bat Our main batch file.

call env.bat
call print.bat
pause

Now print.bat batch file to print variables. Its contents given below

echo %name%

The only way I have found this to work is to launch a new cmd window from my own config window. eg:

@echo off
echo Loading...
setlocal enabledelayedexpansion
call 1.cmd
call 2.bat
...
...
if "%LocalAppData%"=="" set LocalAppData=%UserProfile%\Local Settings\Application Data
SET BLAHNAME=FILE:%LocalAppData%\BLAH
call blah blah
cmd

The last cmd will launch a new cmd prompt with the desired settings exported to the command window.

Here's a workaround for some limited use-cases. You can read-in a file of commands and execute them in-line. For example the calling command file looks like:

echo   OFF
SETLOCAL  ENABLEDELAYEDEXPANSION
     :
echo.         ----------------
echo.           set-up java
echo.         ----------------
echo.
rem       call    %DEV_SCRIPTS%\setup-java
for /F "tokens=*" %%A in ( %DEV_SCRIPTS%\setup-java.bat ) do (
    %%A
)        
call    %DEV_SCRIPTS%\show-java
     :

In the setup-java.bat file you can't use % expansion. You need to use !; e.g.:

    set  JRE_HOME=!JRE_08!
    rem        
    set  JRE_TARGET=!JRE_HOME!

So you are litterally source-ing commands from a text file. You will need to test which commands sourced in this way. It took a few trials just to set some environment variables.

I don't think we can do logic or loops because the command processor scans the file at the start. I am OK just having a simple workaround to reuse shared things like environment definitions. Most other things won't need an actual source command (I am hoping). Good luck.

elGuru

For example to set VC# vars

C:\Windows\System32\cmd.exe /k "C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\vcvarsall.bat"

Use git bash for windows, it works totally fine!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!