是否可以将FOR语句嵌入到IF ELSE语句中?
即
我正在阅读用于定义软件版本的变量。如果有版本指定,哪个有效。但是,如果它是空白的,那我就是寻找最高的文件夹编号。
到目前为止,我有:
IF %Softupgradeversion%=="" (
for /f "tokens=*" %%1 in ('dir /b /ad /on *') do (set latestdir=%%1
)) ELSE (
SET latestdir=%Softupgradeversion%
)
但是,如果变量为空白,则它不起作用并寻找最高的文件夹编号。我会这样,因为FOR语句中的()以及IF ELSE()中的()#。有没有像一个可以像^(' dir / b / ad / on *' ^)那样工作的转义字符
答案 0 :(得分:1)
变量为空白谓词相当于变量未定义,例如在命令行方面:
==>set Softupgradeversion
Environment variable Softupgradeversion not defined
要在批处理脚本中检查该谓词:
if "%Softupgradeversion%"=="" (
echo Softupgradeversion is empty
) else (
echo "%Softupgradeversion%"
)
或
if not defined Softupgradeversion (
echo Softupgradeversion is empty
) else (
echo "%Softupgradeversion%"
)
请注意if "%Softupgradeversion%"==""
中正确的双引号。
事实上,if €%Softupgradeversion%€==€€
甚至if €%Softupgradeversion%==€
对€
几乎所有字符几乎都有相同的效果。但是,双引号是最安全的方式,因为变量可以包含空格,甚至是一些应该escaped的CLI特殊字符,如下所示:
==>set "unusual=a space"
==>if "%unusual%"=="a space" echo good
good
==>if [%unusual%]==[a space] echo good
space]==[a was unexpected at this time.
甚至
==>set "unusual=& > < |"
==>set unusual
unusual=& > < |
==>echo "%unusual%"
"& > < |"