how can i get the directory from which the executable is started?
cd Hello
mycommand
i want to get the directory where the user is when the user start the command.
how can i get the directory from which the executable is started?
cd Hello
mycommand
i want to get the directory where the user is when the user start the command.
Try FileManager.default.currentDirectoryPath
for current working directory (CWD) or Bundle.main.bundlePath
for execution path.
or
Bundle.main.bundlePath
for execution path.
You have to be careful about this because Bundle
contains a lot of complex logic and so the path you get back can change depending on the file system hierarchy in which your tool is placed.
My go-to API for this is _NSGetExecutablePath
. Admittedly, this isn’t easy to call from Swift:
func mainExecutable() -> URL {
var buf = [CChar](repeating: 0, count: Int(MAXPATHLEN))
var bufSize = UInt32(buf.count)
let success = _NSGetExecutablePath(&buf, &bufSize) >= 0
if !success {
buf = [CChar](repeating: 0, count: Int(bufSize))
let success2 = _NSGetExecutablePath(&buf, &bufSize) >= 0
guard success2 else { fatalError() }
}
return URL(fileURLWithFileSystemRepresentation: buf, isDirectory: false, relativeTo: nil)
}
However, even this isn’t with its challenges. To quote the doc comment in <mach-o/dyld.h>
:
Note that
_NSGetExecutablePath
will return "a path" to the executable not a "real path" to the executable. That is the path may be a symbolic link and not the real file.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"