Windows OS

Recommended: Batch File “If” and “If Else” Statements: How to Use the Conditional Statements in Batch Scripts

In batch scripts, the conditional statements, most commonly called as “if” and “else” statements, are used to determine which commands to execute based on the results of a condition. The use of conditional statements in batch scripting enables the developers to create a decision-making logic depending upon the result of the conditions.

The “IF” Statement

The general syntax to write a conditional statement or “if” statement is as follows:

if [condition to check] [command]

The condition is a Boolean expression with only two possible results: True or False. If the condition meets the criteria or True, the command or block that is indicated in the “if” statement is executed. The command is not executed or skipped if the criterion is false.

If the condition that is indicated in the “if” statement is false, the “else” statement is utilized to carry out a specific action. It displays the following:

if [condition to check] [command]
else [command]

Example 1:

The following batch script checks to see if the %USERNAME% variable is equal to “Administrator”. If so, a message that states “You are System Administrator” is displayed by the script. If not, a message that states “You are not an administrator” is displayed by the script.

@echo off
if "%USERNAME%" == "Administrator" (
  echo You are System Administrator
) else (
  echo You are not an administrator
)

Here is the output of the batch script file when using the command prompt:

Example 2:

A typical scenario involves writing a batch script that checks for the presence of particular web browsers on a Windows PC and takes action accordingly. The three well-known web browsers – Google Chrome, Microsoft Edge, and Mozilla Firefox – are tested for presence in the example batch script that is provided in the following. It shows a notification based on which browsers are installed:

@echo off
setlocal enabledelayedexpansion
:: Check for Google Chrome
reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Google\Chrome" > nul 2>&1
if !errorlevel! equ 0 (
    echo Google Chrome is installed on this PC.
) else (
    echo Google Chrome is not installed on this PC.
)
:: Check for Mozilla Firefox
reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Mozilla\Mozilla Firefox" > nul 2>&1
if !errorlevel! equ 0 (
    echo Mozilla Firefox is installed on this PC.
) else (
    echo Mozilla Firefox is not installed on this PC.
)
:: Check for Microsoft Edge (Chromium-based)
reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Edge" > nul 2>&1
if !errorlevel! equ 0 (
    echo Microsoft Edge is installed on this PC.
) else (
    echo Microsoft Edge is not installed on this PC.
)
endlocal

The “ELSE IF” Statement

We can also use the “else if” statement to specify multiple conditions. An “else if” statement is entered as follows:

if [condition to check] [statement block]
else if [condition to verify] [statement block]
else [statement block]

Suppose we’re writing a program (a batch script in Windows) to monitor the age of our users and then display the statements that indicate whether they are children, teenagers, or adults. Here’s a code that we use:

@echo off
setlocal enabledelayedexpansion
:: Prompt the user to enter their age
set /p "UserAge=Enter your age in years: "
:: Check the age and display a message
if !UserAge! lss 13 (
    echo You are a child.
) else if !UserAge! lss 20 (
    echo You are a teenager.
) else (
    echo You are an adult.
)
Endlocal

Use the command prompt to navigate the working directory, type “CheckUserAge.bat”, and then click the “Enter” key to run the batch script code. Numerous outputs from various inputs are shown in the following:

Batch File “If Else” Example to Determine Whether a Variable Is Defined

The “if” and “else” conditional statements in a batch file can be used to check if a variable is defined or not:

Code Explanation:
The batch script checks if a variable is defined and prints its value.

  • The @echo off phrase is useful for hiding the commands that are being run by preventing the script from displaying any of its own lines as output.
  • The next line, setlocal enabledelayedexpansion, tells the script to enable the delayed expansion. This means that the variables will not be expanded until they are actually used. This is useful for preventing errors when the variables are not yet defined.
  • The next section of the script checks if the “myVar” variable is defined. If it is defined, the script echoes the “myVar is defined, and its value is: !myVar!” message. The exclamation mark (!) before a variable’s name indicates that the script is going to expand it immediately.
  • If the “myVar” variable is not defined, the script echoes the “myVar is not defined” message.
  • The next line, IF “%myVar%”==”” (SET myVar=Hello), checks if the “myVar” variable is empty. If it is empty, the script sets the variable to the “Hello” value.
  • The last line displays the value on the command line screen.
@echo off
setlocal enabledelayedexpansion
:: Check if a variable is defined
if defined myVar (
    echo myVar is defined, and its value is: !myVar!
) else (
    echo myVar is not defined.
)
IF "%myVar%"=="" (SET myVar=Hello)
echo %myVar%
endlocal

Working Screenshot:

Batch File “If Else” Example to Verify the Existence of a File or Folder

Special statements can be applied to batch scripts to determine the presence of a file or folder in a specific path.

@echo off
:: Specify the path to the file or folder you want to check
set "file_folder_Path=D:\Work\Arguments\Backup"
:: Check if the file or folder exists
if exist "%file_folder_Path%" (
    echo The file or folder exists.
) else (
    echo The file or folder does not exist.
)

The previous script determines the following:

  1. To set a destination file or folder path, the “folder_Path” variable is specified in the second line of your batch script. This variable is used in the conditional statement after that.
  2. To verify that the provided file or folder is in that location, use the conditional statement which, in this case, is the “if” statement.
  3. If that is the case, it executes the directives in the first set of brackets and displays the “The file or folder exists” message. Without a file or folder, it executes the “else” block and prints the “The file or folder does not exist” message on the command prompt screen.
  4. We should supply the real path to the file or folder that you want to verify. This script can check if the system already contains the required file or folder.

Use the Run (Window + R) keys to open the command prompt and press the “Enter” key after typing “cmd” to run a batch script in Windows. Next, go to the working directory where the “ExistsDir.bat” file is located. It is currently located on drive D. Press “Enter” after entering the batch file’s entire name. If the specified directory exists or not, the output is displayed on the screen as follows:

Conclusion

The conditional statements in batch scripts offer a means of limiting the batch script’s execution and enabling the decisions depending on predetermined criteria. The developers may automate the operations and make the batch scripts adaptive to many scenarios using the conditional batch scripting which leads to more flexible and dependable solutions.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content