用于使用 swift 和 swift-sh 编写脚本的命令行实用程序

贝壳 ⌘

命令行实用程序,用于使用 swift 和swift-sh

注意:在 macOS 上测试,在 iOS 上构建

安装迅捷⇥

$ brew install swift-sh

使用外壳 ⇢

#!/usr/bin/swift sh
import Shell // neutralradiance/shell

let str = "Hello World!"
echo(str, color: .green, style: .bold)

用于检查某些文件或文件夹是否存在的示例脚本 ⏎

#!/usr/bin/swift sh
import Shell // neutralradiance/shell

guard arguments.notEmpty else {
 exit(1, "expected at least one input path")
}

help =
 """
 checks whether or not a folder or file exists
 usage: exists [flags] [locations]
 
 flags:
 -d directory, all locations must be directories (doesn't seem to work)
 -f file, all locations must be files
 
 returns: true or false
 """

var requireFolder = false
var requireFile = false

arguments.removeAll(where: { argument in
 if argument.hasPrefix("-") {
  switch argument.dropFirst() {
  case "h", "help": exit()
  case "d", "directory":
   requireFolder = true
   return true
  case "f", "file":
   requireFile = true
   return true
  default: return false
  }
 } else { return false }
})

let files = FileManager.default
print(
 arguments.allSatisfy {
  var isFolder: ObjCBool = false
  guard files.fileExists(atPath: $0, isDirectory: &isFolder) else { return false }
  return
   requireFolder ? isFolder.boolValue :
   requireFile ? !isFolder.boolValue : true
 }
 .description
)

Credits

  • mxcl for creating swift-sh and chalk
  • Files for making it easier to handle files in scripts

GitHub

点击跳转