How to Check if a Specified Environmental Variable Contains a Substring

John Wachira Feb 02, 2024
How to Check if a Specified Environmental Variable Contains a Substring

This article discusses how we can use the Batch command to test if a certain environmental variable contains a specific substring. We will cover two Batch scripts we can use in the scenario mentioned above.

Check if a Specified Environmental Variable Contains a Substring

Assuming we have an environmental variable defined as Foo and want to check if it contains the substring BAR. How do we go about it?

We can use the trusted findstr command in such a scenario, as illustrated below.

echo.%Foo%|findstr /C:"BAR" >nul 2>&1 && echo Found || echo Not found.

You can branch instead of echoing, but if you require numerous statements based on that, the following is simpler.

echo.%Foo%|findstr /C:"BAR" >nul 2>&1
if not errorlevel 1 (
   echo Found
) else (
    echo Not found.
)

The above script will return Found if the variable contains the specified substring. It will return Not found if the variable does not contain the substring.

In a nutshell, we have covered two scripts we can use to test if a certain environmental variable contains a specific substring.

Author: John Wachira
John Wachira avatar John Wachira avatar

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

Related Article - Batch Variable

Related Article - Batch String