View source code
Display the source code in std/path.d from which this page was generated on github.
Report a bug
If you spot a problem with this page, click here to create a Bugzilla issue.
Improve this page
Quickly fork, edit online, and submit a pull request for this page. Requires a signed-in GitHub account. This works well for small changes. If you'd like to make larger changes you may want to consider using local clone.

Function std.path.expandTilde

Performs tilde expansion in paths on POSIX systems. On Windows, this function does nothing.

string expandTilde (
  string inputPath
) nothrow @safe;

There are two ways of using tilde expansion in a path. One involves using the tilde alone or followed by a path separator. In this case, the tilde will be expanded with the value of the environment variable HOME. The second way is putting a username after the tilde (i.e. ~john/Mail). Here, the username will be searched for in the user database (i.e. /etc/passwd on Unix systems) and will expand to whatever path is stored there. The username is considered the string after the tilde ending at the first instance of a path separator.

Note that using the ~user syntax may give different values from just ~ if the environment variable doesn't match the value stored in the user database.

When the environment variable version is used, the path won't be modified if the environment variable doesn't exist or it is empty. When the database version is used, the path won't be modified if the user doesn't exist in the database or there is not enough memory to perform the query.

This function performs several memory allocations.

Parameters

NameDescription
inputPath The path name to expand.

Returns

inputPath with the tilde expanded, or just inputPath if it could not be expanded. For Windows, expandTilde merely returns its argument inputPath.

Example

void processFile(string path)
{
    // Allow calling this function with paths such as ~/foo
    auto fullPath = expandTilde(path);
    ...
}

Example

version (Posix)
{
    import std.process : environment;

    auto oldHome = environment["HOME"];
    scope(exit) environment["HOME"] = oldHome;

    environment["HOME"] = "dmd/test";
    writeln(expandTilde("~/")); // "dmd/test/"
    writeln(expandTilde("~")); // "dmd/test"
}

Authors

Lars Tandle Kyllingstad, Walter Bright, Grzegorz Adam Hankiewicz, Thomas Kühne, Andrei Alexandrescu

License

Boost License 1.0