Command Line Arguments in COBOL

Command-line arguments are a common way to parameterize execution of programs. For example, CALL "PROGRAM" USING ARG1 ARG2 uses ARG1 and ARG2 as arguments to the PROGRAM.

       IDENTIFICATION DIVISION.
       PROGRAM-ID. COMMAND-LINE-ARGUMENTS.
       ENVIRONMENT DIVISION.
       DATA DIVISION.
       WORKING-STORAGE SECTION.
       01 WS-ARGS-COUNT      PIC 9(4) COMP.
       01 WS-ARG             PIC X(100).
       
       LINKAGE SECTION.
       01 LS-ARGS.
          05 LS-ARG-LENGTH   PIC 9(4) COMP.
          05 LS-ARG-VALUE    PIC X(100).
       
       PROCEDURE DIVISION USING LS-ARGS.
           PERFORM DISPLAY-ARGS
           PERFORM DISPLAY-SPECIFIC-ARG
           STOP RUN.

       DISPLAY-ARGS.
           ACCEPT WS-ARGS-COUNT FROM ARGUMENT-NUMBER
           DISPLAY "Total arguments: " WS-ARGS-COUNT
           PERFORM VARYING WS-ARG-INDEX FROM 1 BY 1
                   UNTIL WS-ARG-INDEX > WS-ARGS-COUNT
               ACCEPT WS-ARG FROM ARGUMENT-VALUE
               DISPLAY "Argument " WS-ARG-INDEX ": " WS-ARG
           END-PERFORM.

       DISPLAY-SPECIFIC-ARG.
           MOVE 3 TO WS-ARG-INDEX
           ACCEPT WS-ARG FROM ARGUMENT-VALUE
           DISPLAY "Third argument: " WS-ARG.

In COBOL, we don’t have direct access to command-line arguments like in some other languages. Instead, we use the ACCEPT FROM ARGUMENT-NUMBER and ACCEPT FROM ARGUMENT-VALUE statements to retrieve the number of arguments and their values.

The DISPLAY-ARGS paragraph shows how to access all arguments:

  1. We use ACCEPT WS-ARGS-COUNT FROM ARGUMENT-NUMBER to get the total number of arguments.
  2. We then loop through all arguments using a PERFORM VARYING loop.
  3. For each iteration, we use ACCEPT WS-ARG FROM ARGUMENT-VALUE to get the value of the current argument.

The DISPLAY-SPECIFIC-ARG paragraph demonstrates how to access a specific argument (in this case, the third one):

  1. We set WS-ARG-INDEX to 3 to get the third argument.
  2. We then use ACCEPT WS-ARG FROM ARGUMENT-VALUE to retrieve its value.

To experiment with command-line arguments, you would compile this program and then run it with arguments. The exact command might vary depending on your COBOL compiler and environment, but it could look something like this:

$ cobc -x command-line-arguments.cob
$ ./command-line-arguments a b c d
Total arguments: 4
Argument 1: a
Argument 2: b
Argument 3: c
Argument 4: d
Third argument: c

Note that in COBOL, unlike some other languages, the program name itself is typically not included in the argument list.

Next, we’ll look at more advanced command-line processing techniques in COBOL.