Paths to do-file in Stata
Several years has passed but the answer is still the same: there is no direct way to determine the location of a current do-file. The discussion around this topic has been raised many times on the Statalist. You can find plenty of useful tips here (just a brief overview, more discussion on the Statalist):
In addition to those and Nick Cox and Fr. answers, I propose my humble solution to a collaborative work in Stata (that works on different machines both on Windows and Linux). It does not require additional modules and depends only on how you organize your materials in folders.
Tip 1. cd to your working directory with a hint -cap- and keep the -cd- code in the beginning of a do-file:
cap cd "W:\Bonds\" //Collaborator 1
cap cd "C:\Users\StataUser\Desktop\ProjectForBonds\" //Collaborator 2
cap cd "/media/DATA/work_materials/Dropbox/MyProjects/Bonds/" //Collaborator 3: Linux machine
cap cd "D:/work_materials/Dropbox/MyProjects/Bonds/" //Collaborator 3: PC
cap cd "E:/Projects/Dropbox/MyProjects/Bonds/" //Collaborator 3: Laptop
-cap-
evades possible errors if a directory does not exist, so every user will get to his own working directory of the project. After -cd-ing to that directory you can save the path as a global variable and use it further in the code (if that is necessary):
global cdpath = "`c(pwd)'"
di "$cdpath" //show current folder
di `"{browse `"$cdpath"':Current folder}"' //optional: click to open the folder in the explorer
Hint: as Nick Cox mentioned, use "/" instead of "\". When you combine "\" with global/local variables, Stata treats this as a combination with an escape symbol (to be able to use symbols like ` and $ in strings), so using "\" may corrupt your browsing strategy. Check it via this code:
global cdpath = "`c(pwd)'"
di "$cdpath"
local i = 1
cap noi use "$cdpath\`i'\auto", clear
cap noi use "$cdpath/`i'/auto", clear
Tip 2. Keep the same folder structure by creating directories within Stata:
cap mkdir "./Temp"
cap mkdir "./Graphs"
Where "."
means the current working directory. So you create "Temp" and "Graphs" folders inside the working directory. There you can store your temporary datasets, place graphs, etc.
You don't need to worry if a directory exists: -cap-
alleviates this issue.
Tip 3. When saving/opening/deleting files (data, graphs, logs, etc.) explicitly tell Stata to use the relative paths:
use "./SourceData", clear
graph export "./Graphs/RollingBond.png", as(png) replace
save "./Temp/Years.dta", replace
save "./FinalBond.dta", replace
cap erase "./Temp/Years.dta"
Stata will know that you are still in your root folder and work relative to that folder.
And of course you can write full paths like this:
save "$cdpath/Temp/FinalBond.dta", replace
These tips work on both Windows and Unix and only requires to write for a new user the -cap cd "..."-
. Very useful when you or your collaborator work from a thumbdrive and don't have access to any other place on a computer.