windows - Windows批处理脚本:提示后if语句不一致
问题描述
我正在编写一个简单的 Windows 批处理脚本来(git)克隆存储库。在其中,我有一个if
不一致的声明:
1 @echo off
2 REM git clone a repo from M:\repo and the checkout the dev branch
3
4 if [%1] EQU [] (
5 echo Usage:
6 echo clone.bat [name_of_repo] [optional: destination_path]
7 goto EXIT
8 )
9
10 set dest_path="."
11 set repo=%1%
12
13 if NOT [%2] EQU [] (
14 set dest_path=%2%
15 )
16
17 if NOT EXIST M:\repo\%repo% (
18 echo Error: repository %repo% does not exist.
19 goto EXIT
20 )
21
22 if NOT EXIST %dest_path% (
23 echo Info: destination %dest_path% does not exist.
24 set /p ans="Create path (Y/n)? "
25 if "%ans%" == "Y" (
26 goto RUN
27 )
28 echo Path not created. Done.
29 goto EXIT
30 )
31
32 :RUN
33 REM test that parameters are set
34 echo %dest_path%
35 echo %repo%
36
37 :EXIT
(我插入了行号以帮助讨论。希望它们不会妨碍您)
脚本非常简单:
- 第 4-8 行 :检查是否为脚本提供了至少一个参数
- 第 10-15 行:设置存储库的名称和可选的目标路径。
- 第 17-20 行:如果 repo 不存在则退出
- 第 22-30 行:应该检查目标路径是否存在,如果不存在,则提示用户创建它。这就是问题所在。
在第 24 行set /p ans="Create path (Y/n)? "
,我提示创建路径并将用户的响应设置为变量ans
。
然后,如果响应为“Y”,则脚本将1创建路径然后转到RUN
,否则它应该退出。
当我按原样重复运行脚本时,我得到了这个:
bcf@AVA-411962-1 E:\
$ clone gpsrx fake_path
Info: destination fake_path does not exist.
Create path (Y/n)? Y
Path not created. Done.
bcf@AVA-411962-1 E:\
$ clone gpsrx fake_path
Info: destination fake_path does not exist.
Create path (Y/n)? Y
fake_path
gpsrx
bcf@AVA-411962-1 E:\
$
我已经尝试了该if
声明的许多变体。而且,我玩过setlocal EnableDelayedExpansion
/setlocal DisableDelayedExpansion
废话。
谁能指出问题是什么?
1我还没有添加mkpath %dest_path%
(在第 25 行和第 25 行之间),因为我不希望脚本在它正常工作之前实际执行任何操作。
解决方案
这里有一些代码供你学习?
@Echo Off
Rem git clone a repo from M:\repo and the checkout the dev branch
If "%~1"=="" (
Echo Usage:
Echo %~nx0 [name_of_repo] [optional: destination_path]
Timeout 5 /NoBreak>Nul
Exit /B
)
Set "repo="
If Exist "M:\repo\%~1\" (
Set "repo=%~1"
) Else (
Echo Error: repository %1 does not exist.
Timeout 3 /NoBreak>Nul
Exit /B
)
Set "dest_path="
If Not "%~2"=="" Set "dest_path=%~2"
If Not Exist "%~2\" (
Echo Info: destination %2 does not exist.
Choice /M "Create path"
If ErrorLevel 2 (
Echo Path not created. Done.
Timeout 3 /NoBreak>Nul
) Else MD "%~2"
)
Rem test that parameters are set
Echo=%dest_path%
Echo=%repo%
Pause
推荐阅读
- excel - 循环变成无穷大并导致excel崩溃
- html - HTML 页眉和页脚:从一处编辑多个文件
- python - Scrapy将链接的请求合并为一个
- php - 如何使用 FPDF PHP 代码直接显示打印页面?
- angular - angular 6子路由组件未加载?
- asterisk - 星号中单个调用的多个唯一标识
- javascript - 无法在生产网络上卷曲网站,只能在 localhost - php 中工作
- css - 为什么1em不是基于定义的16px?
- python-sphinx - 如何使用 sphinx 分配案例的标签中心?
- python - IOError: ('http 错误', 403, 'Forbidden',
)