cmd中复制文件COPY
命令一般都不会有问题,但是如果把COPY
放在IF ELSE
中可能导致批处理文件无法运行。
测试场景
文件夹结构如下:
test
|—folder1
|—|—a(b).txt
|—folder2
选择是否从folder1文件夹复制a(b).txt文件到folder2文件夹。
测试1
不进行选择交互,直接复制,脚本如下:
1 | @echo off & setlocal EnableDelayedExpansion |
保存为test.bat文件后执行结果:
1 | 已复制 1 个文件。 |
copy复制语句似乎没有问题。
测试2
修改以上脚本,添加选择交互:
1 | @echo off & setlocal EnableDelayedExpansion |
保存为test.bat文件后执行,发现一闪而过,看不到什么报错。
解决
经过多次测试,发现将copy中的路径用双引号(“”)包裹起来就可以了。
1 | @echo off & setlocal EnableDelayedExpansion |
由此可见,应该是路径中某些符号没有转义导致的,目测是文件名中的()
,修改脚本,用^
将()
转义:
1 | @echo off & setlocal EnableDelayedExpansion |
运行结果:
1 | 是否复制(0:否,1:是): 1 |
总结
虽然测试1中直接执行复制没问题,但是,将同样的语句放入IF ELSE中居然无法执行,还很难定位问题在哪里,所以解决方法是最好把路径放在双引号(“”)里面,就不用担心这个问题了,如果不这样就在IF ELSE中的路径把特殊字符转义。附上CMD中特殊字符转义说明。
Character to be escaped | Escape Sequence | Remark |
---|---|---|
% | %% | May not always be required in doublequoted strings, just try |
^ | ^^ | May not always be required in doublequoted strings, but it won’t hurt |
& | ^& | May not always be required in doublequoted strings, but it won’t hurt |
< | ^< | May not always be required in doublequoted strings, but it won’t hurt |
> | ^> | May not always be required in doublequoted strings, but it won’t hurt |
‘ | ^’ | Required only in the FOR /F “subject” (i.e. between the parenthesis), unless backqis used |
` | ^` | Required only in the FOR /F “subject” (i.e. between the parenthesis), if backq is used |
, | ^, | Required only in the FOR /F “subject” (i.e. between the parenthesis), even in doublequoted strings |
; | ^; | Required only in the FOR /F “subject” (i.e. between the parenthesis), even in doublequoted strings |
= | ^= | Required only in the FOR /F “subject” (i.e. between the parenthesis), even in doublequoted strings |
( | ^( | Required only in the FOR /F “subject” (i.e. between the parenthesis), even in doublequoted strings |
) | ^) | Required only in the FOR /F “subject” (i.e. between the parenthesis), even in doublequoted strings |
! | ^^! | Required only when delayed variable expansion is active |
“ | “” | Required only inside the search pattern of FIND |
\ | \\ | Required only inside the regex pattern of FINDSTR |
[ | \[ | Required only inside the regex pattern of FINDSTR |
] | \] | Required only inside the regex pattern of FINDSTR |
\ | \\ | Required only inside the regex pattern of FINDSTR |
. | \. | Required only inside the regex pattern of FINDSTR |
* | \* | Required only inside the regex pattern of FINDSTR |
? | \? | Required only inside the regex pattern of FINDSTR |
参考:http://www.robvanderwoude.com/escapechars.php
将表格快速转换为HTML,Markdown格式:http://www.tablesgenerator.com/