为什么 Windows 批处理文件中的换行符导致括号无法识别?

为什么 Windows 批处理文件中的换行符导致括号无法识别?

我正在使用 Windows 10 版本 1709。

我有一个包含以下内容的批处理文件:

@echo off

dir nonexisting_file_or_dir || ^
(
    echo a
    echo b
)
echo c

我得到的是

File Not Found
'(' is not recognized as an internal or external command,
operable program or batch file.
a
b
c

来自以下问题这个,我理解^允许换行,那么为什么括号无法识别呢?

答案1

您正在使用未打开的命令块断开线路,该命令块由||运算符,与您问题中的链接不同,它回答了如何中断命令行并且不适用于您的命令块。

:: Your command syntax ::
dir file ||  ^     ==>    your command   operator   unopened block
                            dir file       ||         ^

:: The syntax should be ::
dir file || ( ^    ==>    your command   operator   opened block   break line
                            dir file       ||         (              ^

:: The syntax trick should be ::
dir file || <nul ^ ==>    your command   operator   trick part   break line
                            dir file       ||         <nul           ^

- 命令行:

dir /b nonexisting_file_or_dir || echo\command in one line && echo\another command
  • 是一样的:
dir /b nonexisting_file_or_dir || ^
echo\command in break line & echo\another command

::  Or...

dir /b nonexisting_file_or_dir ^
|| echo\command in break line && echo\another command

dir /b nonexisting_file_or_dir ^
|| (echo\command in break line & echo\another command)
  • 使用括号的一个命令块:
dir /b nonexisting_file_or_dir || ( 
echo\this is 
echo\your commands block 
echo\on the break line
)

echo\Try it...
  • 使用断线的命令块:
dir /b nonexisting_file_or_dir ^
 || echo\This is ^
 && echo/your command ^
 && echo/block ^
 && echo/on the ^
 && echo/break line ^
 && echo/You don't need (^)

echo\Try it...

这可能对你有用,通过添加<nul...

@echo off

dir nonexisting_file_or_dir || <nul ^
(
    echo a
    echo b
)
echo c

相关内容