How to Check for Empty Variables in Batch
This article illustrates how we can test whether a variable is set. We can employ the if
statement to check whether a variable has been defined.
Check if Variable Is Empty in Batch
For easier context, we will begin by defining two strings, i.e., str1
and str2
. Our first string will be empty (not defined), while the second string will have values (non-empty).
Here is the script we will use.
@echo off
set str1=
set str2=Delft
::using the if statement, we will check whether str1 is an empty string.
if [%str1%]==[] echo "str1 is an empty string"
if [%str2%]==[] echo "str2 is an empty string"
pause
- We have used
set
to get our input string wherebystr1
has no value whilestr2
has the valueDelft
. - We then use the
if
statement to test if our strings are empty.
Note that we do not use parenthesis since they are insecure. Instead, we use square brackets.
We normally use a double colon ::
to add a comment in Batch scripts. The pause
at the end will hold the CMD window until we press a key.
The @echo off
instructs the command prompt not to display the command included in the Batch file, including itself.
Below is the output of our Batch script.
As expected, our first string is empty.
In a nutshell, we can use the if
statement to check if strings or variables are set or, in other words, defined. Remember to use square brackets instead of parenthesis or double quotations.
John is a Git and PowerShell geek. He uses his expertise in the version control system to help businesses manage their source code. According to him, Shell scripting is the number one choice for automating the management of systems.
LinkedIn