[swift-corelibs-dev] Better integration with UNIX tools

Abhi Beckert me at abhibeckert.com
Thu Nov 16 17:33:59 CST 2017


Swift is a great shell scripting language except for it's lack of any
API to execute UNIX commands. Compare these two shell scripts:
> #!/usr/bin/php
> <?
> 
> $files = `find ~/Desktop -name *.png`;
> 
> foreach (explode("\n", $files) as $file) {
>   // do something with $file
> }

-

> #!/usr/bin/swift
> 
> import Foundation
> 
> let process = Process()
> process.launchPath = "/usr/bin/find"
> process.arguments = [
>   NSString(string:"~/Desktop").expandingTildeInPath,
>   "-name",
>   "*.png"
> ]
> 
> let output = Pipe()
> process.standardOutput = output
> 
> process.launch()
> 
> let files: String
> if let filesUtf8 = NSString(data:
> output.fileHandleForReading.readDataToEndOfFile(), encoding:
> String.Encoding.utf8.rawValue) {>   files = filesUtf8 as String
> } else {
>   files = NSString(data:
>   output.fileHandleForReading.readDataToEndOfFile(), encoding:
>   String.Encoding.isoLatin1.rawValue) as NSString! as String> }
> 
> files.enumerateLines { file, _ in
>   // do something with file
> }

It's a contrived example, I could have used NSFileManager, but I
run into this all the time integrating with more complex tools
such as rsync.
Adding my own high level wrapper around the Process command isn't an
option since there is no good way to import code from another file when
executing swift asa shell script. All your code needs to be in one file.
- Abhi
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-corelibs-dev/attachments/20171117/536c53bd/attachment.html>


More information about the swift-corelibs-dev mailing list