Create file in Bash Terminal from Swift

2019-07-27 01:22发布

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条回答
Ridiculous、
2楼-- · 2019-07-27 01:43

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

查看更多
登录 后发表回答