在具有%var%的IF命令行上“(此时出乎意料。”)的原因是什么?

问题描述 投票:1回答:2

当我启动下面发布的批处理文件时,我收到了此错误(此时此刻意外。 我认为这发生在IF命令行if %ad%==60 (但我不确定。

(此时出乎意料。

@echo off
color 0f
title TITLE
mode con cols=50 lines=25
set ad = 0

set s = 0
set m = 0
set h = 0
set d = 0

if exist start.txt (
    del start.txt
    goto :1
) else (
    exit
)
:1
if %ad%==60 (
:: Something here
set ad = 0
)

:: MINUTES
if %s%==60 (
set /a m=m+1
set s = 0
)
:: HOURS
if %m%==60 (
set /a h=h+1
set m = 0
)
:: DAYS
if %h%==24 (
set /a d=d+1
set h = 0
)

cls
echo Something here...
timeout 1 > nul
set /a ad=ad+1
set /a s=s+1
goto :1

执行批处理文件时出现此错误消息的原因是什么?

batch-file cmd
2个回答
4
投票

作为一个开始,

set ad = 60

不会将ad设置为60。它将变量adspace设置为space60,将ad留给脚本开始之前的任何内容。

在你的情况下,它几乎肯定是一个空字符串,因为由此产生的命令将与下面的记录中的命令相同(注意生成的错误):

d:\pax> if ==60 (
( was unexpected at this time.

如果你想要间隔很好的表达式,你已经知道如何做到这一点,因为你用它来增加h。换一种说法:

set /a "ad = 0"

2
投票

这在技术上不是一个答案,(已经充分提供)。这只是一个示例,向您展示如何选择性地缩短脚本:

@Echo Off
Color 0F
Title TITLE
Mode 50,25

Set /A ad=s=m=h=d=0

If Not Exist "start.txt" Exit /B
Del "start.txt"

:1
If %ad% Equ 60 (
    Rem Something here
    Set "ad=0"
)

Rem Minutes
If %s% Equ 60 Set /A m+=1,s-=60
Rem Hours
If %m% Equ 60 Set /A h+=1,m-=60
Rem Days
If %h% Equ 24 Set /A d+=1,h-=24

ClS
Echo Something here...
Timeout 1 >Nul
Set /A ad+=1,s+=1
GoTo :1

笔记: 1.使用Timeout 1不会增加时钟(精确的秒数),它将大约是一秒加上再次通过:1所花费的时间。 2.小​​心不要陷入Set /A的八进制陷阱,确保你的变量中没有领先的0

© www.soinside.com 2019 - 2024. All rights reserved.