batch-file - 文件不断被删除
问题描述
我在使用我的批处理程序时遇到问题,其中有 2 个if
语句,其中一个语句允许用户向日志文件添加注释,而另一个if
语句则完全删除日志文件。
这取决于用户他们选择哪个选项,但是当我运行文件时,即使我输入选项 1 以向日志文件添加注释而不是删除它,它似乎也会删除我的日志文件。
echo loggedTime = %time% %date%>> log.txt
REM This is for the 2 scenarios the user has to choose from
echo Please make your choice:
set /p choice1=
REM This takes the user's input and adds it to the end of the text file
IF %choice1%== 1 echo Please enter your comment:
set /p comment=
echo %comment%>> log.txt
REM this deletes the log file altogether
IF %choice1%== 2 echo The log file is being deleted
cd C:\Users\.....
del log.txt
解决方案
The command interpreter reads every line in the script unless you structure your script in a way that prevents this.
This most common ways of achieving this is through the use of code blocks (Lines of code contained within parentheses) and Labels to 'skip' lines. When taking user input, through set /p, you need a method to validate it, and return for new input if the input doesn't match the Conditional tests your using.
There is a better way still to achieve all of these points, and thats combining the Choice
Command with Labels in the form of subroutines as follows:
@Echo off
Goto :main
REM Script break created by the label Jump
REM Subroutines
:Choice[1]
Echo(loggedTime = [%time% %date%]>>"%temp%\Mylog.txt"
set /p comment=Comment:
echo("%comment%">>"%temp%\Mylog.txt"
Exit /B
:Choice[2]
del "%temp%\Mylog.txt"
Exit /B
:Choice[3]
IF exist "%temp%\Mylog.txt" (TYPE "%temp%\Mylog.txt")
Exit /B
REM main body of the script
:main
REM /N : Hide options prompt
REM /C : Define options (options will be assigned errorlevel according to occurance after /C switch)
REM /M "prompt string" : Define Custom prompt for the choice
CHOICE /N /C cdv /M "add (C)omment (D)elete Log (V)iew Log"
REM Calls the selected subroutine. Exit /B within the Subroutine resumes the script from after the call
CALL :Choice[%errorlevel%]
pause
Exit /B
推荐阅读
- kvm - UDP 错误校验和错误
- elasticsearch - ElasticSearch - 使用 WHERE 子句一次更新多个文档
- javascript - Cron Job 每天运行多次
- python - 获取有关灰色图像中彩色像素的信息。蟒蛇,opencv
- c# - 如何检查C#中嵌套的JSON解析对象中是否存在键
- shell - gcloud 使用时间戳过滤器登录 CLI
- xcode - 如何隐藏我认为来自版本控制的这些蓝色标记?
- reactjs - React Bundle 给出错误:“类型错误:无法读取未定义的属性 'ReactCurrentOwner'”
- arrays - 视觉基本<>问题
- haskell - Haskell 递归函数