16

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.

Zev Eisenberg
  • 8,080
  • 5
  • 38
  • 82

2 Answers2

21

The accepted answer doesn't work in Swift 3. Also, this is a more straightforward approach:

import Foundation

let currentDirectoryURL = URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
let url = URL(fileURLWithPath: CommandLine.arguments[1], relativeTo: currentDirectoryURL)
print("script at: " + url.path)

However, it has the same problem pointed out by @rob-napier, if the script's directory is in your PATH.

ganzogo
  • 2,516
  • 24
  • 36
  • This works almost perfectly in Swift 3, but `CommandLine.arguments[0]` contains the script name (in Zev's question). You want `CommandLine.arguments[1]`, which would contain the name of the passed path/script. – worthbak Dec 13 '16 at 16:52
9

just in swift:

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

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

//get script working dir
if script.hasPrefix("/") { //absolute
    let path = (script as NSString).deletingLastPathComponent
    print("\n\nscript at:\n" + path)
} else {
    let urlCwd = URL(fileURLWithPath: cwd)
    if let path = URL(string: script, relativeTo: urlCwd)?.path {
        let path = (path as NSString).deletingLastPathComponent
        print("\n\nscript at:\n" + path)
    }
}
Anton Belousov
  • 1,140
  • 15
  • 34
Daij-Djan
  • 49,552
  • 17
  • 113
  • 135
  • 2
    Note that this will fail if use use #! and it's in PATH (but it does match the way the OP says to run the script, so that's ok) – Rob Napier Jul 17 '15 at 16:35
  • @RobNapier what do you mean? I do have `#!/usr/bin/env swift` at the top, but that's not in my `$PATH` – Zev Eisenberg Jul 17 '15 at 16:36
  • I mean if script.swift is in your PATH, then just calling "script.swift" will make it look like the script is in whatever directory you're currently in. – Rob Napier Jul 17 '15 at 16:37