为什么批处理脚本变量在FOR循环中保持不变?

时间:2017-01-25 06:22:14

标签: windows batch-file windows-7 windows-nt

我们需要使用批处理脚本来控制startstoprestartstatus等守护程序,其中CKI_SYSTEM_STAT是可变的,基于守护进程的条件。在这里,我们必须根据问题模拟它以实现。 CKI_SYSTEM_STAT随机更改,但在for循环内,它在stop标签下保持不变。

因此,在执行停止操作时,我们无法检测到守护程序是否已成功停止。以下是您需要考虑的批处理脚本。

rem ebisd.bat

@echo off
if "%OS%" == "Windows_NT" setlocal
set "CKI_OPTION_NAME=%1"

call :init_ebis
call :ebis_case
goto :eof

:init_ebis
rem initialization of varible
if "%CKI_DAEMON_NAME%" == "" set "CKI_DAEMON_NAME=Demon"
goto :eof

rem fetch the process info
:init_meta
rem init flag
SET /A CKI_RANDOM_NUMB=%RANDOM%%%10
echo Random Number %CKI_RANDOM_NUMB%
if %CKI_RANDOM_NUMB% lss 7 (
  set "CKI_SYSTEM_STAT=stoped"
) else (
  set "CKI_SYSTEM_STAT=runing"
)
goto :eof


:ebis_case
rem label ebis_case
call :init_meta
set "CKI_SWITCH_CASE=false"
for %%i in (start stop status restart) do (
  if %%i'==%CKI_OPTION_NAME%' SET "CKI_SWITCH_CASE=true"
)
if "%CKI_SWITCH_CASE%" == "false" call :message
if "%CKI_SWITCH_CASE%" == "true"  call :case_%CKI_OPTION_NAME%
goto :eof


:case_start
rem label case_start
call :start
goto :eof


:case_stop
rem label case_stop
call :stop
goto :eof


:case_status
rem label case_status
call :status
goto :eof


:case_restart
rem label case_restart
call :restart
goto :eof


:start
rem label start
if "%CKI_SYSTEM_STAT%" == "runing" (
  echo %CKI_DAEMON_NAME% already %CKI_SYSTEM_STAT%
)

if "%CKI_SYSTEM_STAT%" == "stoped" (
  echo %CKI_DAEMON_NAME% is starting
)
goto :eof


:status
rem label status
echo %CKI_DAEMON_NAME% is %CKI_SYSTEM_STAT%
goto :eof


rem label stop
:stop
if "%CKI_SYSTEM_STAT%" == "stoped" (
  echo %CKI_DAEMON_NAME%    %CKI_SYSTEM_STAT%
)

if "%CKI_SYSTEM_STAT%" == "runing" (
  echo %CKI_DAEMON_NAME%   stoping
  for /L %%a in (0,1,5) do (
    call :init_meta
    call :status
    if %%a lss 5 (
      if "%CKI_SYSTEM_STAT%" == "runing" (
        timeout 3 > NUL
        echo Wrong is %CKI_SYSTEM_STAT%
        echo .
      )
      if "%CKI_SYSTEM_STAT%" == "stoped" (
        echo stoped
        goto :eof
      )
    )
    if %%a equ 10 (
      echo unable to  stop
    )
  )
)
goto :eof


:restart
rem label restart
call :stop
call :start
goto :eof


rem label message
:message
echo Usage^: start^|stop^|^status^|restart
goto :eof


:freeze
rem label freeze
@pause
goto :eof

为了您的实现,我通过调用循环内的status标签来模拟它,以查看CKI_SYSTEM_STAT的实际值也在CKI_SYSTEM_STAT循环内回显for的值stop标签。但是CKI_SYSTEM_STAT循环中for保持不变。这是控制台输出:

c:>batch\ebisd.bat stop
Random Number 8
Demon   stoping
Random Number 2
Demon is stoped
Wrong is runing
.
Random Number 4
Demon is stoped
Wrong is runing
.
Random Number 8
Demon is runing
Wrong is runing
.
Random Number 9
Demon is runing
Wrong is runing
.
Random Number 4
Demon is stoped
Wrong is runing
.
Random Number 4
Demon is stoped

脚本内部可能存在错误或无法实现变量的范围。如果有人帮助我们找出这个脚本的问题/错误,那将是值得注意的。非常期待的替代解决方案。

0 个答案:

没有答案