windows – 带双引号的批处理文件多行命令

前端之家收集整理的这篇文章主要介绍了windows – 带双引号的批处理文件多行命令前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
使用^符号输入带有参数的多行命令时使用双引号来使用带空格的字符串^符号也会被传递,有人可以解释这是什么方式吗?

working.cmd

  1. @echo off
  2. call openfiles.cmd ^
  3. C:\dir\filename.txt ^
  4. C:\another_dir\another_file.txt

notworking.cmd

  1. @echo off
  2. call openfiles.cmd ^
  3. "C:\dir with spaces\file with spaces.txt" ^
  4. "C:\another dir with spaces\another file with spaces.txt"

openfiles.cmd看起来像

  1. @echo off
  2. for %%x in (%*) do (
  3.  
  4. IF EXIST %%x (
  5. call "c:\Program Files\Notepad++\notepad++.exe" %%x
  6. ) ELSE (
  7. call echo Not found %%x
  8. )
  9.  
  10. )
  11.  
  12. pause

我得到的错误

  1. C:\>call openfiles.cmd "C:\dir with spaces\file with spaces.txt" ^
  2. ELSE was unexpected at this time.
问题是,第二行开头的引号将被多行插入符号转义.
因此,行中的最后一个引号开始引用而不是停止引用,因此第二行中的插入符号作为普通字符处理.
  1. call openfiles.cmd ^"C:\dir with spaces\file with spaces.txt" ^
  2. **This is a seperate line** "C:\another dir with spaces\another file with spaces.txt"

插入符号规则:

插入符号逃脱了下一个角色,因此角色会失去所有特效.
如果下一个字符是换行符,则删除此字符并取下一个字符(即使这也是换行符).

通过这个简单的规则,你可以解释像

  1. echo #1 Cat^&Dog
  2. echo #2 Cat^
  3. &Dog
  4. echo #3 Redirect to > Cat^
  5. Dog
  6.  
  7. setlocal EnableDelayedExpansion
  8. set lineFeed=^
  9.  
  10.  
  11. echo #4 line1!lineFeed!line2

#3创建了一个名为“Cat Dog”的文件,因为空间已被转义,不再作为分隔符.

但它仍有可能打破这个规则!
你只需要在插入符号前面放置任何重定向,它仍然会丢弃换行符(多行仍然有效),但下一个字符不再被转义.

  1. echo #5 Line1< nul ^
  2. & echo Line2

所以你也可以使用它来构建你的多线命令

  1. call openfiles.cmd < nul ^
  2. "C:\dir with spaces\file with spaces.txt" < nul ^
  3. "C:\another dir with spaces\another file with spaces.txt"

或者使用宏

  1. set "\n=< nul ^"
  2. call openfiles.cmd %\n%
  3. "C:\dir with spaces\file with spaces.txt" %\n%
  4. "C:\another dir with spaces\another file with spaces.txt"

猜你在找的Windows相关文章