How to use relative paths in Stata
This guide shows you how to write a Stata do-file whose file paths keep working when you move it between your own computer and LINCOMM (Linux Community Servers). Stata is the easiest package for this: it reads relative paths from the current working directory, so the trick is simply to run Stata from your project folder. For the concept behind this, see Understanding relative paths.
Prerequisites
- A Stata do-file and its data files, kept together in one project folder.
Steps
-
Lay out your project so the data sits in a known place relative to the do-file:
myproject/ analysis.do data/ survey.xlsx -
In
analysis.do, refer to data with paths relative to the project folder — no drive letters, no/mnt/...:import excel "data/survey.xlsx", sheet("Sheet1") firstrowUse
..to go up a folder. For example, to read a file from asharedfolder that sits next to your project:import excel "../shared/regions.xlsx", firstrow -
On LINCOMM, move into the project folder before launching Stata, so the working directory matches your relative paths:
cd /mnt/aae/users/jdoe/myproject stata -b do analysis.doThe
cdhere is the Linux command that sets your working folder;stata -b dothen runs the do-file from that folder.
Verify it worked
Copy the whole myproject folder to LINCOMM, change into it, and run the do-file:
cd /mnt/aae/users/jdoe/myproject
stata -b do analysis.doIt should load survey.xlsx and run without any path edits. Check analysis.log in the same folder to confirm the data loaded.
If something went wrong
- "file ... could not be opened": You're probably running Stata from the wrong folder. Run
cdinto the project folder first, then start Stata. Stata reads relative paths from wherever it was launched. - Works on your computer but not on LINCOMM: Check that the data folder was copied along with the do-file, and that names match exactly (Linux is case-sensitive, so
Dataanddataare different).