I want to run a shell script from Swift.

Asked 2 years ago, Updated 2 years ago, 40 views

How do I run a shell script from Swift?
Also, I would like to wait for Swift to finish executing the shell script.

swift

2022-09-30 19:07

3 Answers

Use the NSTask class.
WaitUntilExit is waiting for the script to end.

import Foundation

let task = NSTask.launchedTaskWithLaunchPath("/bin/sh", arguments: ["-c", "sleep3" ])
task.waitUntilExit()


2022-09-30 19:07

Is the following description acceptable?

let task=NSTask.launchedTaskWithLaunchPath("./test.sh", arguments: ["-c", "sleep3" ])

task.waitUntilExit()

In this case, where should test.sh be located in the X-Code project?


2022-09-30 19:07

let task = NSTask.launchedTaskWithLaunchPat
("/bin/sh", arguments: ["-c", "xxxxx.sh")
task.waitUntilExit()

Make the xxxxx.sh part the appropriate shell macro.
Write the xxxxx.sh part in full path.

Now it's working. Thank you.


2022-09-30 19:07

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.