Get path to Swift script from within script

前端 未结 2 1266
庸人自扰
庸人自扰 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: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)
        }
    }
    

提交回复
热议问题