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?
Run the Swift File With Parameters The CommandLine enumeration is part of the Swift standard library to provide the command line arguments. We use CommandLine.arguments to get the parameters after the swift command. 4. Using ‘swiftc’ to Make the Executable File
The current working directory is the directory from which you invoke commands in your terminal. The pwd command is used to display the current working directory. If you have any questions or feedback, feel free to leave a comment.
If you run the same command using the -P option: The command will print the directory to which the symlink points to: The current working directory is the directory from which you invoke commands in your terminal. The pwd command is used to display the current working directory.
The CommandLine enumeration is part of the Swift standard library to provide the command line arguments. We use CommandLine.arguments to get the parameters after the swift command. 4. Using ‘swiftc’ to Make the Executable File In the Swift world, there are two steps to make the Swift file executable: compile and link.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With