BudiBadu Logo
Samplebadu

COBOL by Example: Environment Variables

COBOL 2002

Reading operating system environment variables with ACCEPT FROM ENVIRONMENT, configuring programs dynamically based on runtime context, handling missing variables with space checks, and integrating with modern deployment scenarios for configuration.

Code

       IDENTIFICATION DIVISION.
       PROGRAM-ID. ENV-VARS.
       
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01  USER-NAME   PIC X(20).
       
       PROCEDURE DIVISION.
           DISPLAY "Reading USERNAME from OS...".
           ACCEPT USER-NAME FROM ENVIRONMENT "USERNAME".
           
           IF USER-NAME = SPACES
               DISPLAY "Variable not found."
           ELSE
               DISPLAY "Hello, " USER-NAME
           END-IF.
           STOP RUN.

Explanation

COBOL programs often need to interact with their host operating system. The ACCEPT statement is used to retrieve data from outside the program. While it can read from the console (stdin), it is also used to read environment variables.

The syntax ACCEPT variable FROM ENVIRONMENT "VAR_NAME" allows the program to configure itself dynamically based on the runtime environment. This is essential for modern deployment scenarios, such as reading database connection strings, API keys, or user identities from the container or OS environment.

Always handle the case where the environment variable is missing. In standard COBOL, the behavior might vary (e.g., the variable remains unchanged or is filled with spaces), so explicit checks are recommended to ensure the program behaves predictably.

Code Breakdown

9
ACCEPT USER-NAME FROM ENVIRONMENT "USERNAME". Queries the OS for the environment variable named "USERNAME" and stores the result in USER-NAME.
11
IF USER-NAME = SPACES. If the environment variable doesn't exist, the receiving field usually remains unchanged or is filled with spaces (implementation dependent).
14
DISPLAY "Hello, " USER-NAME. Prints the value if it was found.