I want to replace my CI bash scripts with swift. I can't figure out how to invoke normal terminal command such as ls
or xcodebuild
#!/usr/bin/env xcrun swift
import Foundation // Works
println("Test") // Works
ls // Fails
xcodebuild -workspace myApp.xcworkspace // Fails
$ ./script.swift
./script.swift:5:1: error: use of unresolved identifier 'ls'
ls // Fails
^
... etc ....
If you don't use command outputs in Swift code, following would be sufficient:
Updated: for Swift3/Xcode8
Mixing rintaro and Legoless's answers for Swift 3
Full script based on Legoless's answer
Updating for Swift 4.0 (dealing with changes to
String
)The problem here is that you cannot mix and match Bash and Swift. You already know how to run Swift script from command line, now you need to add the methods to execute Shell commands in Swift. In summary from PracticalSwift blog:
The following Swift code will execute
xcodebuild
with arguments and then output the result.As for searching the directory contents (which is what
ls
does in Bash), I suggest usingNSFileManager
and scanning the directory directly in Swift, instead of Bash output, which can be a pain to parse.If you would like to use command line arguments "exactly" as you would in command line (without separating all the arguments), try the following.
(This answer improves off of LegoLess's answer and can be used in Swift 4 Xcode 9.3)