首页 > 解决方案 > Check if dynamic variable is empty - Batch

问题描述

I want to check, if a dynamic variable is empty. I have the variables f1-f9 and now I want to check like this:

IF f%ERRORLEVEL%=" " //do something

But this doesnt work. I also tried:

IF !f%ERRORLEVEL%!

But this doesn't work either.

EDIT:

The variables f1-f9 are created like this:

set "f1= "
set "f2= "
...

%ERRORLEVEL% contains a number between 1-9 (comes from a choice command)

标签: batch-filevariables

解决方案


You are trying to match the value of f1 which is with " " So simply fix it by adding souble quotes around %f1% see example:

IF %ERRORLEVEL%==1 (
    IF "%f1%"==" " (
        set "f1=%turn%"
    ) ELSE (
        goto draw_screen
    )

But as per you question to simply your script, you firstly need delayedexpansion and then some straighforward if testing:

@echo off
setlocal enabledelayedexpansion
set "f1= "
set "f2= "
set "f3= "
set "errorlevel=2"

if "!f%errorlevel%!"==" " (
    set "f%errorlevel%=%turn%"
) else (
    goto draw_screen
)

I use f1-3 only for simplifying the answer and obvisouly mimicing errorlevel as a test. It is a single if statement which will match any errorlevel, you can test it by changing errorlevel value above.


推荐阅读