ajaygandhari
ajaygandhari

Reputation: 11

Check for Empty/has only spaces for string in batch script

Please see the below code Example :

can anyone provide a solution???

I have a batch script that has few variables containing values such as strings and numbers. Sometimes, I am getting an empty string or a string containing only spaces as input. I want to deploy condition to filter out those cases.

 set Test_String = "   "

if Test_String=="empty/contains only spaces" 
//(do nothing )
else
//(do something)

I would like to get the solution for this to deploy in .bat file

Upvotes: 1

Views: 2407

Answers (2)

dbenham
dbenham

Reputation: 130819

Compo's IF solution with find/replace is probably the simplest and best performing method.

But FOR /F might be a good solution if you need to parse the value. For example, the default delims of space will effectively trim leading and trailing spaces.

FOR /F will not iterate a string if it is empty or contains only spaces/tabs. The EOL option should be set to space so that lines beginning with ; are not falsely missed (thanks Stephan for your comment). So if you want to do something with non-empty, but nothing upon empty (or blank), then

for /f "eol= " %%A in ("%VAR%") do (
  echo VAR is defined and contains more than just spaces or tabs
)

If you want to take action upon empty (or space value), then you can take advantage of the fact that FOR /F returns a non-zero value if it does not iterate. You must enclose the entire FOR construct in parentheses to properly detect the empty condition. And you should make sure the last command of the DO clause always returns 0.

(
  for /f "eol= " %%A in ("%VAR%") do (
    echo VAR is defined and contains more than just spaces or tabs
    rem Any number of commands here
    (call ) %= A quick way to force a return code of 0. The space after call is critical =%
  )
) || (
  echo VAR is not defined or contains only spaces/tabs
)

Upvotes: 4

Compo
Compo

Reputation: 38589

First thing you need to learn is how to set a variable using preferred/recommend syntax. Set "Test_String= " will define a variable named Test_String to a value of a single space, whereas set Test_String = " " will define the variable %Test_String % with a value of  " ".

You could perform a character replacement, replacing a space character with nothing, then your verification will be against an undefined/empty string:

@Set /P "Test_String=Please enter a string here to test against:"
@If "%Test_String: =%" == "" (Echo empty/contains only spaces) Else Echo do something
@Pause


A variable cannot have no value, it either has one or is not defined, so if you want to know whether the end user had made an entry at the prompt for input, then you could do it like this:

@Set "Test_String="
@Set /P "Test_String=Please enter a string here to test against:"
@If Not Defined Test_String (Echo no entry was made) Else Echo an entry was made
@Pause

Upvotes: 2

Related Questions