I want to develop an app to promote the experience when using terminal on Mac. And I want to get the current working directory (cwd) from terminal. How can I implement it?
I notice that the answer in Get terminal output after a command swift is really good but it seems that it still cannot resolve my problem perfectly. I learned Process().currentDirectoryPath
from Apple's document https://developer.apple.com/reference/foundation/process Does it do the trick that I need? Can I use it like the following?
let path = Process().currentDirectoryPath
I am very new to swift and Xcode, please help me! Thanks!
Update: Thank you guys! It seems that both
let path = fileManager.default.currentDirectoryPath
and the Process()
one temporarily work for me. Are there any differences between these two?
I had this same question and went with the latter option:
let path = FileManager.default.currentDirectoryPath
To answer your updated question, the difference between the Process()
and the FileManager
approaches is that the Process().currentDirectoryPath
approach prepares to create a new subprocess and then tells you the working directory that subprocess will use. The subprocess would have the same working directory as the parent process, of course, but it's wasteful to create a new Process
instance just to find the working directory.
Definitely use the FileManager
approach, as that returns the working directory that is used by the current process without creating any subprocesses or any other overhead.
Sources:
https://developer.apple.com/documentation/foundation/filemanager/1409234-default
https://developer.apple.com/documentation/foundation/filemanager/1410766-currentdirectorypath