How to pass text with new line as parameter to a b

2019-05-03 08:50发布

问题:

If I pass text like this:

first line
second line

to a .bat file, it is taking the first line only as a parameter value.

How can I fix this? Thanks

回答1:

It is nearly impossible to pass a newline within a batch file argument. It can be done, but I don't think anyone has developed a pragmatic way to properly read such a parameter within a batch file.

Your best bet is to define an environment variable that contains the two lines of text, including the newline. Then pass the name of the variable as an argument to the batch and then let the batch file access the value using delayed expansion.

test.bat:

@echo off
setlocal enableDelayedExpansion
echo !%1!

From the command line:

>set multiLine=hello^
More?
More? world

>test multiLine
hello
world

For anyone interested, here is a discussion initiated by jeb concerning newlines in batch parameters: http://www.dostips.com/forum/viewtopic.php?t=1768



回答2:

You can access all parameters, but only if the batch files is started with cmd /c, ex. like a drag&drop action.

@echo off
setlocal EnableDelayedExpansion
echo !cmdcmdline!

But if you start the batch file from the prompt, then this will not work as cmdcmdline contains only how the cmd.exe was started, in that case it's normally something like "C:\Windows\system32\cmd.exe".