Monday, February 27, 2017

Hack 4.14 Running System Commands from a SAS Program


SAS Programming Professionals,

Did you know that you can execute Windows operating system commands from within a SAS Data step?

You can do this by using the CALL SYSTEM call routine.  Unlike its blunt cousin the X statement, CALL SYSTEM can be executed conditionally within a DATA step.  This makes it much more flexible and useful.  Here is an example:

/* Rename directory on Mondays*/
data _null_;

if weekday(today()) = 2 then do;

      call system("rename c:\temp\mikedir mikedir_old");
      call system("md c:\temp\mikedir");

end;

run;

ods rtf file="c:\temp\mikedir\classlist.rtf";

proc print noobs data=sashelp.class;
title1 "List of Subjects in Weight/Height Study";
run;

ods rtf close;

In the example, the DATA _NULL_ step houses the CALL SYSTEM call routines.  They are only executed when the current day of the week is Monday.  When they are executed, the first CALL SYSTEM sends a command to Windows to rename the MIKEDIR directory to MIKEDIR_OLD.  The second CALL SYSTEM sends a command to Windows to create a new directory named MIKEDIR.  The subsequent PROC PRINT creates an RTF file in the new MIKEDIR directory.

Obviously, the Windows system commands must be syntactically correct for the CALL SYSTEM call routine to work properly.  Here is one of the many online sources for looking up Windows system commands:


The previously mentioned X command executes unconditionally.  That means that if we were to replace both CALL SYSTEM’s with X commands in the program above, they would executed no matter what day of the week it is.  They just barge right in.  That is why I prefer the CALL SYSTEM call routine for shelling out operating system commands from within my SAS programs.

Best of luck in all your SAS endeavors!

---MMMMIIIIKKKKEEEE
(aka Michael A. Raithel)
Author of the new cult classic for computer programmers:  It Only Hurts When I Hit <ENTER>
Print edition:  http://tinyurl.com/z8bzx2e 
Kindle edition: http://tinyurl.com/zypgqa7 

The hack above is an excerpt from the book:  Did You Know That?  Essential Hacks for Clever SAS Programmers

No comments:

Post a Comment