Mastering External Commands in REXX Programming Language

Mastering External Commands in REXX Programming: A Comprehensive Guide

Hello, fellow programming enthusiasts! In this blog post, I will introduce you to External Commands in REXX Programming – an essential aspect that enhances scri

pt functionality. External commands allow REXX programs to interact with the operating system, execute system commands, and integrate with other programs. Understanding how to invoke and manage these commands is crucial for writing efficient automation scripts. I will walk you through the syntax, execution methods, and error handling techniques to ensure seamless command execution. By the end, you’ll gain a solid grasp of how REXX interacts with external commands to streamline various tasks. Let’s get started!

Table of contents

Introduction to External Commands in the REXX Programming Language

REXX is a powerful scripting language widely used for automation, text processing, and system administration. One of its essential features is the ability to interact with external commands and programs, making it highly versatile in various computing environments. REXX allows users to invoke external commands and programs using various methods. The most common way is by issuing a command directly within a script. On different operating systems, REXX interacts with external commands through the command interpreter or shell. The ADDRESS statement is used to direct commands to a specific command environment, such as the default operating system shell.

For example, in Windows, ADDRESS CMD "dir" lists the directory contents, while in Unix/Linux, ADDRESS SH "ls -l" does the same. REXX scripts can also execute external programs using the CALL instruction, such as CALL SYSTEM 'ping google.com' to check connectivity. Capturing output from external commands can be done using LINEIN, allowing further processing of command results. Error handling is facilitated by the RC variable, which stores the return status of the last executed command. These features make REXX a valuable tool for system automation and scripting.

What are External Commands in REXX Programming Language?

REXX (Restructured Extended Executor) is a high-level scripting language that provides powerful capabilities to interact with the operating system, execute external commands, and automate tasks. External commands in REXX refer to system-level commands, shell commands, or programs that REXX scripts can invoke to extend functionality.

Direct Execution of External Commands

REXX allows direct execution of system commands within the script. If a command is not recognized as a REXX instruction, REXX assumes it is an external command and attempts to execute it using the system shell.

Example: Running a System Command

On Windows

/* REXX script to list files */
'DIR'

On Linux/Unix

/* REXX script to list files */
'ls'
  • When a command like 'DIR' or 'ls' is written inside a REXX script, REXX passes it to the operating system for execution.
  • The command runs just like it would in a command-line interface (cmd.exe on Windows or sh on Linux).
  • The result of the command is displayed on the screen.

Using the ADDRESS Instruction

The ADDRESS instruction in REXX allows directing commands to a specific environment or command processor.

Syntax: Using the ADDRESS Instruction

ADDRESS environment command
  • environment: Specifies where to send the command (e.g., SYSTEM, CMD, SH, TSO, ISPEXEC).
  • command: The external command to execute.

Example: Running a Command with ADDRESS

On Windows

ADDRESS CMD 'dir'

On Linux/Unix

ADDRESS SYSTEM 'ls'
  • ADDRESS CMD (Windows) or ADDRESS SYSTEM (Unix/Linux) explicitly tells REXX where to execute the command.
  • This ensures the command is processed by the correct command interpreter.

Running External Programs

Apart from shell commands, REXX can execute external programs such as Notepad, Calculator, or any executable file.

Example: Running External Applications

On Windows

/* Open Notepad */
ADDRESS CMD 'notepad.exe'
/* Open Calculator */
ADDRESS CMD 'calc.exe'

On Linux

/* Open gedit text editor */
ADDRESS SYSTEM 'gedit &'
  • These commands launch external programs just like running them from a command line.
  • In Linux, the & symbol runs the command in the background, so the REXX script continues execution.

Capturing Output of External Commands

Sometimes, you need to capture the output of a command and use it in the REXX script.

Method 1: Redirect Output to a File

We can redirect command output to a file and read it back in REXX.

Example: Capturing Directory Listing

/* Run DIR command and save output */
ADDRESS CMD 'DIR > output.txt'

/* Read output file */
DO WHILE LINES('output.txt') > 0
    line = LINEIN('output.txt')
    SAY line
END
CALL LINEOUT 'output.txt'  /* Close file */
  • The command DIR > output.txt saves the directory listing to output.txt.
  • The script then reads and prints the contents of the file.

Method 2: Using PIPE (Unix/Linux)

In some REXX implementations (like Regina REXX on Linux), you can use pipes to capture command output directly.

ADDRESS SYSTEM 'ls | tee output.txt'
  • This runs ls, and the tee command saves the output to output.txt while displaying it on the screen.

Handling Return Codes

Each external command returns a status code, which can be accessed using the RC variable.

Example: Checking Return Code

ADDRESS CMD 'mkdir new_folder'
SAY 'Return Code: ' RC
  • If RC = 0, the command executed successfully.
  • If RC ≠ 0, an error occurred.

Example: Handling Errors

ADDRESS SYSTEM 'mkdir existing_folder'
IF RC \= 0 THEN
   SAY 'Error: Folder may already exist!'
  • If mkdir fails, the script displays an error message.

Advanced Usage: Running Multiple Commands

You can execute multiple commands in sequence.

Example: Creating a Backup

backup_folder = 'backup_' || DATE('S')
ADDRESS CMD 'mkdir ' backup_folder
ADDRESS CMD 'copy *.* ' backup_folder
SAY 'Backup complete: ' backup_folder
  • Creates a backup folder with a timestamp.
  • Copies all files to the backup folder.

Running Commands in Different Shells

Different platforms have different command processors.

PlatformCommand ShellREXX Syntax
Windowscmd.exeADDRESS CMD
Linux/Unixsh or bashADDRESS SYSTEM
IBM MainframeTSO or ISPFADDRESS TSO

Example: Automating a Task Using External Commands

  • Objective
    • Check if a file exists.
    • If it exists, move it to a backup folder.

REXX Script

file_name = 'important.txt'
backup_folder = 'backup_' || DATE('S')

/* Create backup folder */
ADDRESS CMD 'mkdir ' backup_folder

/* Check if file exists */
ADDRESS CMD 'IF EXIST ' file_name ' MOVE ' file_name ' ' backup_folder

IF RC = 0 THEN
    SAY 'File moved successfully!'
ELSE
    SAY 'Error: File not found!'
  • Displays success or error message based on RC.
  • Creates a backup folder.
  • Checks if important.txt exists and moves it.

Why do we need External Commands in REXX Programming Language?

When working with the REXX programming language, interacting with external commands is essential for automation, system administration, and extending REXX’s functionality. Below are key reasons why we need to work with external commands in REXX:

1. Automating System Tasks

REXX allows running system commands like file operations, directory management, and process automation. For example, creating folders, copying files, and deleting old logs can be automated using system commands like mkdir, copy, and del. This reduces manual work and improves efficiency in repetitive tasks.

2. Interacting with the Operating System

By using external commands, REXX scripts can communicate directly with the operating system. This helps in executing shell commands (CMD in Windows, sh in Linux/Unix) to perform tasks that are not natively supported in REXX. It allows seamless integration between REXX scripts and the system environment.

3. Running External Applications

REXX can execute external programs such as Notepad, Calculator, or custom applications. For example, a script can launch notepad.exe to open a text file or start a web browser with a specific URL. This capability is useful for automating workflows that involve multiple software tools.

4. Capturing and Processing Command Output

External commands generate useful information, such as system status, disk space, and active processes. REXX can capture this output using file redirection (> or |) and process it within the script. For example, listing directory contents (DIR or ls), filtering results, and taking automated actions based on the output.

5. Enhancing Script Functionality with System Utilities

Many operating systems provide built-in utilities (e.g., ping, find, grep) that can enhance REXX scripts. Instead of manually coding search or network testing logic in REXX, these utilities can be used for faster and more efficient operations, making scripts more powerful with minimal effort.

6. Handling File and Directory Management

REXX scripts often need to create, move, delete, or rename files and directories. Using system commands like mkdir, rm, mv, and cp simplifies file handling. This is especially useful in batch processing, backups, and log maintenance tasks.

7. Checking and Controlling Process Execution

REXX can execute and monitor system processes, checking if a specific program is running and terminating processes if needed. Commands like tasklist (Windows) and ps (Linux) help in managing active tasks. This is useful for monitoring system health and resource usage.

8. Running Batch Jobs and Schedulers

External commands enable REXX scripts to schedule and execute batch jobs using system schedulers like cron (Linux) or Task Scheduler (Windows). This allows automation of recurring tasks such as data backups, report generation, and periodic system maintenance.

9. Handling System Configuration and Administration

System administrators use REXX scripts to modify system settings, manage users, configure networks, and update system files. Commands like net user, ipconfig, and hostname allow REXX to perform administrative tasks efficiently.

10. Cross-Platform Scripting and Portability

Using external commands allows REXX scripts to run across different operating systems with minimal modifications. By dynamically detecting the OS and executing platform-specific commands (DIR for Windows, ls for Linux), scripts become more portable and adaptable to different environments.

Example of External Commands in REXX Programming Language

In REXX, working with external commands is essential for interacting with the operating system, automating tasks, managing files, executing programs, and capturing system information. Below are several detailed examples demonstrating how to execute external commands using REXX.

1. Running a Simple System Command

REXX can execute system commands directly by enclosing them in quotes or using the ADDRESS instruction.

Example: Listing Files in a Directory

On Windows
/* List files in the current directory on Windows */
'DIR'
On Linux/Unix
/* List files in the current directory on Linux/Unix */
'ls'
  • The command 'DIR' runs on Windows, while 'ls' is used on Linux/Unix.
  • REXX sends the command to the system shell, and the output is displayed on the screen.

2. Using ADDRESS to Execute Commands

The ADDRESS instruction directs external commands to a specific environment.

Example: Executing Commands Using ADDRESS

On Windows
ADDRESS CMD 'dir'
On Linux/Unix
ADDRESS SYSTEM 'ls -l'
  • ADDRESS CMD ensures the command is executed by cmd.exe (Windows).
  • ADDRESS SYSTEM sends the command to the shell (sh or bash on Linux).
  • The -l flag in Linux provides a detailed file list.

3. Running an External Application

REXX can launch external programs, such as a text editor or a web browser.

Example: Opening Notepad or gedit

On Windows
/* Open Notepad */
ADDRESS CMD 'notepad.exe'
On Linux
/* Open gedit (Text Editor) */
ADDRESS SYSTEM 'gedit &'
  • notepad.exe is launched on Windows.
  • gedit & is used on Linux to open the text editor in the background.

4. Capturing Command Output

REXX can capture the output of external commands and process it within the script.

Example: Capturing Directory Listing

/* Save directory listing to a file */
ADDRESS CMD 'DIR > output.txt'

/* Read the output file */
DO WHILE LINES('output.txt') > 0
    line = LINEIN('output.txt')
    SAY line  /* Print each line */
END

CALL LINEOUT 'output.txt'  /* Close the file */
  • The command DIR > output.txt redirects the output to output.txt.
  • LINEIN() reads each line from the file.
  • The script prints the captured output.

5. Checking Return Codes

External commands return an exit status, which can be accessed using the RC variable.

Example: Checking if a Folder is Created Successfully

ADDRESS CMD 'mkdir test_folder'
SAY 'Return Code:' RC

IF RC = 0 THEN
    SAY 'Folder created successfully!'
ELSE
    SAY 'Error: Unable to create folder!'
  • The command mkdir test_folder attempts to create a directory.
  • The return code (RC) is checked:
    • RC = 0 → Success.
    • RC ≠ 0 → Error.

6. Running Multiple Commands in Sequence

You can execute multiple system commands using ADDRESS instructions.

Example: Creating a Backup Directory and Copying Files

backup_folder = 'backup_' || DATE('S')

/* Create a backup folder */
ADDRESS CMD 'mkdir ' backup_folder

/* Copy files to backup folder */
ADDRESS CMD 'copy *.* ' backup_folder
SAY 'Backup completed in folder: ' backup_folder
  • A backup folder is created with the current date.
  • All files are copied into the backup folder.

7. Checking if a File Exists Before Executing a Command

We can use conditional execution to check if a file exists before performing an action.

Example: Moving a File If It Exists

file_name = 'important.txt'
backup_folder = 'backup_' || DATE('S')

/* Create backup folder */
ADDRESS CMD 'mkdir ' backup_folder

/* Check if file exists before moving */
ADDRESS CMD 'IF EXIST ' file_name ' MOVE ' file_name ' ' backup_folder

IF RC = 0 THEN
    SAY 'File moved successfully!'
ELSE
    SAY 'Error: File not found!'
  • The script first creates a backup folder.
  • The IF EXIST command checks if important.txt exists before moving it.
  • The script handles errors based on RC.

8. Scheduling a Task Using REXX

REXX can interact with the system’s task scheduler to automate repetitive tasks.

Example: Scheduling a Task on Windows

/* Schedule a task to run a REXX script daily */
ADDRESS CMD 'SCHTASKS /CREATE /SC DAILY /TN "MyTask" /TR "C:\Scripts\my_script.cmd" /ST 10:00'
SAY 'Task scheduled successfully!'
  • The SCHTASKS command schedules my_script.cmd to run every day at 10:00 AM.
  • This allows automating system maintenance tasks.

9. Running Network Commands

REXX can execute network-related commands to fetch system information.

Example: Checking System IP Address

On Windows
ADDRESS CMD 'ipconfig'
On Linux
ADDRESS SYSTEM 'ifconfig'
  • The script retrieves and displays network configuration details.
  • Useful for debugging network-related issues.

10. Running Commands in Different Environments

REXX supports multiple execution environments like TSO (for IBM mainframes) and ISPEXEC (for ISPF panels).

Example: Running a TSO Command in REXX (Mainframe)

ADDRESS TSO 'LISTCAT'
  • The command LISTCAT lists catalog entries in an IBM mainframe environment.

Advantages of External Commands in REXX Programming Language

Here are advantages of working with external commands in the REXX programming language:

  1. Expands Functionality Beyond Built-in Features: External commands allow REXX to perform tasks that are not natively supported, such as interacting with system utilities, managing files, or executing third-party applications, enhancing the script’s capabilities.
  2. Seamless Integration with the Operating System: REXX can execute shell commands (DIR, COPY, LS, GREP, etc.) directly, enabling automation of system administration tasks, batch processing, and file management without requiring complex programming.
  3. Simplifies Complex Operations: Instead of writing lengthy code for file handling, network communication, or process management, REXX can call external utilities that are optimized for these tasks, reducing development effort.
  4. Enables Cross-Platform Execution: REXX scripts can be designed to run external commands on different operating systems (Windows, Linux, z/OS) with minimal modifications, making them portable and adaptable to various environments.
  5. Enhances Automation and Batch Processing: By using external commands, REXX can automate repetitive administrative tasks like backups, log analysis, report generation, and data processing, improving efficiency.
  6. Supports Interaction with Other Programming Languages: External commands enable REXX to interact with programs written in other languages (such as C, Python, or Java), allowing seamless integration between different technologies.
  7. Reduces Memory and Processing Load: Instead of handling resource-intensive tasks within REXX, external commands delegate processing to specialized programs, reducing the memory and CPU usage of the REXX script itself.
  8. Provides Access to Advanced Features: External utilities often have advanced capabilities, such as encryption, compression, or database access, which can be leveraged by REXX scripts without requiring additional programming effort.
  9. Allows Execution of Background Processes: External commands can run in the background while the REXX script continues execution, enabling multitasking and parallel processing for better performance.
  10. Improves Maintainability and Modularity: By offloading specific tasks to external utilities, REXX scripts remain simpler and easier to maintain, as functionality can be updated or replaced independently without modifying the core script.

Disadvantages of External Commands in REXX Programming Language

Here are disadvantages of working with external commands in the REXX programming language:

  1. Requires Additional System Configuration: Some external commands may need specific environment variables, permissions, or software installations, adding extra setup steps for users and increasing system configuration complexity.
  2. Dependency on External Tools: Using external commands makes REXX scripts dependent on the availability of specific system utilities or third-party programs. If these commands are missing or incompatible, the script may fail.
  3. Reduced Portability Across Platforms: Some external commands work differently on Windows, Linux, and z/OS. A script that runs fine on one operating system may not work on another without modifications, limiting cross-platform compatibility.
  4. Performance Overhead: Executing external commands requires spawning new processes, which consumes system resources and slows down execution, especially if the script frequently calls external programs.
  5. Limited Error Handling and Debugging: External commands may fail silently or return non-standard error messages, making it difficult for REXX scripts to detect and handle failures effectively. Debugging can be challenging if errors are not properly logged.
  6. Security Risks: Calling external commands, especially with user inputs, can expose the system to security vulnerabilities like command injection attacks. Running commands with elevated privileges can also pose risks if not handled properly.
  7. Complex Output Parsing: External commands often return results in different formats, requiring additional parsing logic in REXX to extract useful information, which can complicate script development.
  8. Potential Compatibility Issues with Future Updates: If an external tool or system command is updated or deprecated in a future OS version, REXX scripts relying on it may break, requiring constant maintenance.
  9. Increased Script Execution Time: Since each external command execution requires launching a new process, it can slow down script execution compared to using built-in REXX functions for similar tasks.
  10. Loss of Control Over Execution: Once an external command is executed, REXX has limited control over its execution. If the external program hangs or crashes, it may cause the script to become unresponsive.

Future Development and Enhancement of External Commands in REXX Programming Language

Here are future developments and enhancements that could improve working with external commands in the REXX programming language:

  1. Improved Cross-Platform Compatibility: Enhancing REXX to provide a standardized way to execute external commands across different operating systems (Windows, Linux, z/OS) would reduce portability issues and minimize OS-specific modifications.
  2. Built-in Command Wrappers: Introducing built-in functions or libraries that act as wrappers for common external commands would allow REXX scripts to execute system operations without relying directly on platform-dependent utilities.
  3. Enhanced Error Handling and Debugging: Future versions of REXX could capture detailed error messages, return codes, and logs from external commands, making it easier to diagnose and recover from failures.
  4. Asynchronous Command Execution: Implementing non-blocking or background execution for external commands would allow REXX scripts to continue running while waiting for long-running processes to complete, improving performance.
  5. Improved Security Mechanisms: Enhancements like automatic input validation, sandboxed execution environments, and privilege management would reduce security risks associated with executing external commands.
  6. Optimized Performance with Process Management: Future updates could introduce process management features that allow REXX to monitor, pause, resume, or terminate external commands dynamically, reducing system overhead and improving control.
  7. Standardized Output Parsing Mechanisms: Built-in support for structured parsing of command outputs (e.g., JSON, XML, CSV) would simplify data extraction, eliminating the need for complex string manipulation in REXX scripts.
  8. Integration with Modern APIs and Web Services: Allowing REXX to interact seamlessly with RESTful APIs, cloud services, and remote command execution tools would expand its capabilities beyond traditional local system commands.
  9. Automated Dependency Management: A built-in package manager for external tools and utilities could help automate installations and updates, ensuring that necessary commands are available and compatible.
  10. Enhanced Logging and Monitoring Capabilities: Future REXX versions could introduce built-in logging frameworks to track external command execution, capturing execution times, errors, and system performance metrics for better monitoring.

Discover more from PiEmbSysTech

Subscribe to get the latest posts sent to your email.

Leave a Reply

Scroll to Top

Discover more from PiEmbSysTech

Subscribe now to keep reading and get access to the full archive.

Continue reading