Create file in Bash Terminal from Swift

删除回忆录丶 提交于 2019-12-11 10:43:41

问题


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 😉


回答1:


Calling that command (/bin/bash touch ~/Desktop/touch.txt) directly in Terminal result in the same error.

/usr/bin/touch: cannot execute binary file

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".



来源:https://stackoverflow.com/questions/52226934/create-file-in-bash-terminal-from-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!