Zev Eisenberg Zev Eisenberg - 2 months ago 7
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:

print(Process.arguments)


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

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)
    }
}
Comments