Zev Eisenberg Zev Eisenberg - 1 year ago 77
Swift Question

Get path to Swift script from within script

I'm writing a script in Swift, and I want it to modify some files that always exist in the same directory as the script itself. Is there a way to get the path to the script from within itself? I tried:


But that outputs only the path that was actually given to the script, which may be the fully resolved path, just the file name, or anything in between.

I'm intending the script to be run with
swift /path/to/my/script.swift

Answer Source

just in swift:

import Foundation

let cwd = NSFileManager.defaultManager().currentDirectoryPath
print("script run from:\n" + cwd)

let script = Process.arguments[0];
print("\n\nfilepath given to script:\n" + script)

//get script working dir
if script.hasPrefix("/") { //absolute
    let path = script.stringByDeletingLastPathComponent
    print("\n\nscript at:\n" + path)
} else {
    let urlCwd = NSURL(fileURLWithPath: cwd)
    if let path = NSURL(string: script, relativeToURL: urlCwd)?.path {
        let path = path.stringByDeletingLastPathComponent
        print("\n\nscript at:\n" + path)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download