title: How can I check if a directory already exists and if not, create it?
body: <p>How can I check if a directory already exists and if not, create it?</p>
  
  <p>I am using a SAS 9.3 server with SAS EG 5.1 under Windows 7.</p>
  
  <pre><code>%macro chk_dir(dir=) ; 
     options noxwait; 
     %local rc fileref ; 
     %let rc = %sysfunc(filename(fileref,&amp;dir)) ; 
     %if %sysfunc(fexist(&amp;fileref))  %then 
        %put NOTE: The directory "&amp;dir" exists ; 
     %else 
       %do ; 
           %sysexec md   &amp;dir ; 
           %put %sysfunc(sysmsg()) The directory has been created. ; 
     %end ; 
     %let rc=%sysfunc(filename(fileref)) ; 
  %mend chk_dir ; 
  </code></pre>
  
  <p>This code comes from the <a href="http://www.sas.com/offices/europe/uk/support/sas-hints-tips/ht1_mar04.html" rel="nofollow">SAS website</a>.</p>
  
  <p>However when I try to create a folder using this macro, <code>%chk_dir(dir=E:\foo\20140904_test);</code>, it fails to create the folder and I get the following log message:</p>
  
  <pre><code>MLOGIC(CHK_DIR):  %SYSEXEC  md   &amp;dir
  SYMBOLGEN:  Macro variable DIR resolves to E:\foo\20140904_test
  ERROR: Shell escape is not valid in this SAS session. 
  MLOGIC(CHK_DIR):  %PUT %sysfunc(sysmsg()) The directory has been created.
  </code></pre>
  
  <p>The directory <code>E:\foo'</code> does exist and calling <code>%chk_dir(dir=E:\foo);</code> gives log output : <code>NOTE: The directory "E:\foo" exists</code> as expected.</p>