Open In App

Batch Script – Working with Environment Variables

Last Updated : 01 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Environment Variables refer to the variables which are globally declared and can be accessed by the processor under the management of OS like Windows, Mac, and Linux. In starting they were meant to store the path locations but now they also work with Batch Script. The data of batch programs like input from CMD prompt, text files, log files, etc are stored under this. The user can easily change the search path using a batch file so that the applications can be run efficiently. If a variable is undefined and a batch file is scanned, some unwanted execution can occur.

An example is given below:-

@echo off
set /p result = Want to say Hello ? (Y/N) ?
if /i "%result:~,1%" EQU "Y" echo Hello Ji!
if /i "%result:~,1% EQU "N" echo Bye Bye
pause

 

  • “Y” input from the user will lead to print hello as mentioned above.
  • “N” input from the user will lead to print bye-bye. 

Benefits of Environment Variables

  • Efficient Execution Performance: It boosts the performance of the batch script so the commands which are executing run in less time and space complexities. 
  • Make script application secure: Credential information got highly secured after using environment variables
  • Reduce Execution mistakes: Runtime execution errors reduces to a large extent after developing environment variables as it configures them properly.

Environment expressions are as follows:

  • %name:~n% – It skips the first “n” letters and returns the remaining.
  • %name:~n,m% – It skips “n” letters and returns the next “m”
  • %name:,m% – Leftmost “m” number of letters.
  • %name:~-m% – Rightmost “m” number of letters.

Output Examples of the above expressions:

 

1.) ECHO  %var% :

 

 

2.) ECHO  %var:~2,3% :

 

 

3.) ECHO  %var:~-3% :

 

 

4.) ECHO  %var:~,3% :

 

 

5.) ECHO  %var:~2%:

 

 


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads