So, I'm trying to write a line of that will check if there is a directory present, and only try and create a directory if that is false. Found this on Statalist:
local name test_directory
cd C:\
capture confirm file "./`name'/nul" // check if `name' subdir exists
if _rc { // _rc will be >0 if it doesn't exist
!md "`name'"
}
// my do file
save "C:/`name'/current_data.dta" // optionally add -,replace-
Looks pretty solid overall for my application, but I'm struggling with converting it to Mac compatible syntax.
local name test_directory
cd ~/
capture confirm file "./`name'/*"
// check if `name' subdir exists
if _rc {
mkdir "`name'"
}
Any advice on how to do this right?
You can try relying on the return code of the cd
command. This is the approach taken by confirmdir
(from SSC):
local somedir /home/roberto/Desktop/test
quietly capture cd `"`somedir'"'
if (_rc) display as text "return code `=_rc'; do something, like mkdir"
else display as text "could change dir; the dir exists"
This will signal if
cd was unable to change to the directory you typed because either it does not exist, it is protected, or it is not a directory
Source: search r(170)
.
If you plan on issuing several commands after the conditionals, then you need the if {...} else {...}
syntax. See help ifcmd
.
If you don't want to end up in a different directory, you can save the current one at the beginning
local cwd `"`c(pwd)'"'
and switch back to it when your done:
quietly cd `"`cwd'"'
It should work on both MS Windows and Unix-type OS. (But I can't test on MS Windows.)