Shell 批处理文件嵌套IF语句帮助-CMD Batch
我目前正在编写一个简单的批处理文件。我对编程并不陌生,但绝对不是专家。这是我第一次使用批处理文件 基本上,我希望一个文件从一个目录移动到另一个目录,如果目标目录中已经有一个同名的文件,它会将其重命名为备份。这样,它将始终保留一个备份,以防此脚本意外运行 经过数小时的代码故障排除,我仍然不知道为什么它不能工作。我怀疑这与嵌套的if语句有关。If语句中的If语句(缺少更好的解释) 我将非常感谢你的帮助。谢谢Shell 批处理文件嵌套IF语句帮助-CMD Batch,shell,batch-file,if-statement,cmd,Shell,Batch File,If Statement,Cmd,我目前正在编写一个简单的批处理文件。我对编程并不陌生,但绝对不是专家。这是我第一次使用批处理文件 基本上,我希望一个文件从一个目录移动到另一个目录,如果目标目录中已经有一个同名的文件,它会将其重命名为备份。这样,它将始终保留一个备份,以防此脚本意外运行 经过数小时的代码故障排除,我仍然不知道为什么它不能工作。我怀疑这与嵌套的if语句有关。If语句中的If语句(缺少更好的解释) 我将非常感谢你的帮助。谢谢 @echo off REM Variables rem dir1 is the sou
@echo off
REM Variables
rem dir1 is the source directory
set dir1=C:\Users\%username%\Desktop\Dir1\
rem dir2 is the target directory
set dir2=C:\Users\%username%\Desktop\Dir2\
rem file is the name of the source file and desired name of the target file
set file=file.txt
rem pre1 is the name of the copy of the old target file before it is overwritten
set pre1=push backup
rem pre2 is the name of prefix for a temporary file created in the target directory
set pre2=temp
REM if source file exist
if exist %dir1%%file% (
rem if there is a file named the same in target directory
if exist %dir2%%file% (
rem if there is allready a backup file
if exist %dir2%%pre1%%file% (
rem rename the backup file as a temp file
rename %dir2%%pre1%%file% %dir2%%pre2%%file%
rem rename the old file as backup file
rename %dir2%%file% %dir2%%pre1%%file%
rem move source file to target directory
move %dir1%%file% %dir2%
rem if rename failed
if not exist %dir2%%file% (
rem rename the backup to the normal file
rename %dir2%%pre1%%file% %file%
rem rename the temp file to the backup file
rename %dir2%%pre2%%file% %pre1%%file%
rem echo error
echo rename error
pause
rem Delete temp file
) else ( del %dir2%%pre2%%file% )
)
) ELSE ( move %dir1%%file% %dir2% )
) ELSE ( echo %file% does not exist in directory "%dir1%" )
pause
为我草率的评论道歉 第一个IF缺少一个else,而第一个IF缺少一个true的正确赞歌 应具有“')else()”以完成语法 由于某种原因,它们现在出现了
为您没有的添加一个else() 将所有文件引用用双引号括起来。否则,用户名或文件名中的空格将破坏大多数批处理脚本 例如,您的
pre1
变量等于push backup
,其中包含一个空格
因此,您的第三个存在测试:
if exist %dir2%%pre1%%file% ( ... )
将转换为(评估其他变量并假设用户名为jack):
这将检查名为:
推
在文件夹中:
C:\Users\jack\Desktop\Dir2\
如果该文件存在,则应执行的命令为:
backupfile.txt(…)
通过将文件引用用双引号括起来:
if exist "%dir2%%pre1%%file%" ( ... )
您将获得所需的支票:
if exist "C:\Users\jack\Desktop\Dir2\push backupfile.txt" ( ... )
请显示您在控制台上遇到的错误我没有收到错误,如果dir1和dir2中有file.txt文件,它将不会移动该文件。可能是因为该文件已经存在,这就是为什么我让它将dir2中的file.txt重命名为“push backup.file.txt”,所以我认为我的else或缩进在某个点上是错误的,我不知道在哪里。感谢您在批处理文件开头看到@echo的帮助。使用REM和reexecute对其进行注释,以查看控制台上的错误。目前,您的问题没有明确的问题陈述,示例代码也不是最少的。感谢savasa,它显示了命令语法不正确的原因。我假设这是指两个重命名命令。听说是截图为什么else()
是多余的。其中一个if语句缺少一个。我认为.bat喜欢所有语法都存在。我认为第一个if语句的缩进没有问题。“if exist%dir1%%file%”(如果存在)下的代码前面有一个选项卡。我认为else()不会改变任何内容,而且似乎没有任何效果。
if exist "C:\Users\jack\Desktop\Dir2\push backupfile.txt" ( ... )