I'm trying to use Swift to run a command in the (macOS) terminal. Specifically, to create an empty file. Here's what I have for running in a shell:
import Foundation
func shell(_ args: String...) ->Int32{
let task = Process()
task.launchPath = "/bin/bash"
task.arguments = args
task.launch()
task.waitUntilExit()
return task.terminationStatus
}
Note that I have tried /usr/bin/env/
for the launch path with no good result.
When I call shell("touch /path/to/new/file.txt")
it returns an error like:
/bin/bash: touch /Users/my_home_dir/Desktop/file.txt: No such file or directory
127
If I change the launch path it gives a very verbose but unhelpful console message Which reminds me of Python typical output <'class 'demo' at 0x577e040ab4f'>
I've even tried running python in the terminal and creating a file with open()
.
I am open to any new ways to create files in Swift (which would be great), and any ways to do the above so that it actually works.
Thanks in advance
Calling that command (
/bin/bash touch ~/Desktop/touch.txt
) directly in Terminal result in the same error.If you only want to call "touch" you can set the launch path to
/usr/bin/touch
and only pass~/Desktop/touch.txt
for the argument.If you want to call general bash/shell commands you pass
-c
followed by the shell command joined as a string so that it corresponds to:/bin/bash -c "touch ~/Desktop/touch.txt"
.