Get path to Swift script from within script

前端 未结 2 1289
庸人自扰
庸人自扰 2021-02-19 22:46

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 fro

相关标签:
2条回答
  • 2021-02-19 23:23

    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.

    0 讨论(0)
  • 2021-02-19 23:27

    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)
        }
    }
    
    0 讨论(0)
提交回复
热议问题