Environment Variables in COBOL

Environment variables are a universal mechanism for conveying configuration information to programs. Let’s look at how to set, get, and list environment variables in COBOL.

IDENTIFICATION DIVISION.
PROGRAM-ID. ENVIRONMENT-VARIABLES.

ENVIRONMENT DIVISION.
CONFIGURATION SECTION.

DATA DIVISION.
WORKING-STORAGE SECTION.
01 WS-ENV-VALUE PIC X(100).
01 WS-ENV-PAIR PIC X(100).
01 WS-ENV-NAME PIC X(50).
01 WS-ENV-VAL  PIC X(50).

PROCEDURE DIVISION.
MAIN-PROCEDURE.
    *> To set a key/value pair, use CALL "SETENV"
    *> To get a value for a key, use CALL "GETENV"
    CALL "SETENV" USING "FOO" "1" 0

    CALL "GETENV" USING "FOO" WS-ENV-VALUE
    DISPLAY "FOO: " WS-ENV-VALUE

    CALL "GETENV" USING "BAR" WS-ENV-VALUE
    DISPLAY "BAR: " WS-ENV-VALUE

    *> To list all environment variables, we need to use
    *> system-specific calls. Here's a conceptual representation:
    DISPLAY " "
    PERFORM VARYING WS-ENV-PAIR FROM 1 BY 1 UNTIL WS-ENV-PAIR = SPACES
        CALL "GET-NEXT-ENV-PAIR" USING WS-ENV-PAIR
        UNSTRING WS-ENV-PAIR DELIMITED BY "="
            INTO WS-ENV-NAME WS-ENV-VAL
        DISPLAY WS-ENV-NAME
    END-PERFORM

    STOP RUN.

In COBOL, working with environment variables typically involves using system-specific calls. The exact method can vary depending on the COBOL implementation and the operating system.

Running the program shows that we pick up the value for FOO that we set in the program, but that BAR is empty.

FOO: 1
BAR:

The list of environment variables will depend on your particular machine:

TERM_PROGRAM
PATH
SHELL
...
FOO

If we set BAR in the environment first, the running program picks that value up. In COBOL, this would typically be done before running the program, as part of the job control language (JCL) or command-line environment setup.

FOO: 1
BAR: 2
...

Note that the exact syntax for setting and getting environment variables can vary between COBOL implementations. Some systems might require you to use special environment access routines or system-specific calls. Always refer to your specific COBOL compiler’s documentation for the most accurate information on working with environment variables.