简体   繁体   中英

How to set an env variable with multiline file content in windows command prompt

I have a file say my-file.dat which has multiple lines. I want to set an env variable say MYVAR that will contain the content of my-file.dat. That is, in windows command prompt, the output of type my-file.dat be same as the output of echo %MYVAR% and with new-line preserved .

In RHEL/MAC, it is typically done like this export MYVAR=$(cat my-file.dat) , but how do I do the similar in windows command prompt (not really interested in powershell, but feel free to share examples it might be my backup option)

Following the answer of this Stackoverflow question Multiline text file, how to put into an environment variable I could get a variable to hold the content of my-file.dat. But this variable's scope seems to be the batch file. Even though I run the batch file from the command prompt, I don't see the batch-file's variable is available in the command prompt.

I tried set /P MYVAR=<my-file.dat , but this sets only the first line whereas I want all lines when I echo MYVAR

Pls help.

The technique you use requires delayed expansion, which is not enabled by default. So the code issues setlocal enableDelayedExpansion . But that localizes environment changes. When the script ends there is an implicit endlocal , and the environment is restored to what existed before the setlocal .

The simplest solution is to run the script in a session where delayed expansion is already enabled so that you can remove setlocal enableDelayedExpansion . You can do this simply by running
cmd /v:on from your command line before executing your script.

There is another simple, but ugly option. The implicit endlocal does not occur if your script has a fatal syntax error (I consider this to be a bug in cmd.exe). So you can put the following at the end of your script:

:: Your current script goes here.
:: I'm assuming your script falls through to the end and does not use EXIT /B

call :fatalErr 2>nul

:fatalErr
if

But I discourage you from using this technique if you might be executing your script multiple times - your dead environments will begin to pile up.

Also - please remember that variables are limited to ~8191 characters - your script will fail if the file you are trying to capture exceeds the limit. This is a hard limit of cmd.exe

Update

You could put the cmd /v:on command within your script if you add the /K option. The IF statement tests if delayed expansion is enabled or not. If not, then it reruns the script via cmd.exe with the /K option and /V:ON.

@echo off
if "!!" neq "" cmd /v:on /k "%~f0"
:: rest of your script goes here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM