Creating command-line tool in Swift
This question comes up often on Swift mailing lists. Once you learn Swift, you’ll get addicted and want to use it everywhere. It’s not quite as straightforward writing a script in Swift as it is in python or bash. However, there are lots of benefits.
- It’s a great entry point into learning Swift for those that typically write scripts rather than applications
- You want to execute a bunch of shell commands, but you can use Swift’s rich data structures, straightforward programming language, and the huge Cocoa API.
Here’s what you can do:
- Launch Xcode
- File > New > ProjectChoose macOS
- Click on Command Line Tool
- Name it and save the project
- Click on main.swift in the sidebar
- Replace the Hello, World line with this code.
import Foundation
struct Shell {
func stripWhitespace(_ inString: String) -> String {
return inString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
func executeCommand(_ command:String, echo: Bool = true) -> String {
let process = Process(); let pipe = Pipe()
(process.standardError, process.standardOutput) = (pipe, pipe)
process.launchPath = "/bin/sh"
process.arguments = ["-c", command]
process.launch()
let handle = pipe.fileHandleForReading
var availableData: Data
var returnString = ""
while true {
availableData = handle.availableData
if availableData.count == 0 { break }
if let string = String(data: availableData, encoding: .utf8) {
if echo == true { print(string, terminator: "") }
returnString = returnString + string
}
}
return stripWhitespace(returnString)
}
}
// example code
var result = Shell().executeCommand("ls")
result = Shell().executeCommand("ls ~", echo: false)
At the bottom are two example lines of code to show how to call a shell command. This is similar to how things work in python with the major exception being that it’s not python.
Extra credit
Create a command-line project in the same way described above. Save this project as a template to be used later. You can then just duplicate the project and then easily just start writing a script.