Function Signature
Description
TheDir() function returns the home directory for the executing user using OS-specific methods. It automatically caches the result for performance, unless caching is disabled via the DisableCache variable.
Return Values
The absolute path to the user’s home directory
An error if the home directory cannot be detected. Returns
nil on success.Behavior
Caching
By default,Dir() caches the home directory after the first successful call. Subsequent calls return the cached value without re-detection. This improves performance for applications that call Dir() frequently.
To disable caching, set DisableCache = true before calling Dir().
Platform-Specific Detection
Windows:- Checks the
HOMEenvironment variable first - Falls back to
USERPROFILEenvironment variable - Finally tries combining
HOMEDRIVEandHOMEPATHenvironment variables - Returns an error if all methods fail
- Checks the
HOMEenvironment variable first (orhomeon Plan 9) - On macOS: Uses
dsclcommand to read the user’s NFSHomeDirectory - On Linux: Uses
getent passwdto read from the password database - Falls back to executing
cd && pwdin a shell - Returns an error if all methods fail
Usage Examples
Basic Usage
With Cache Disabled
Error Handling
The function returns an error when:- All environment variables are empty or blank
- OS-specific commands fail to execute
- The detected home directory is blank
Related
- Expand() - Uses
Dir()internally to expand~in paths - Reset() - Clears the home directory cache
- DisableCache - Configuration variable to disable caching