0Pricing
Swift Academy · Lesson

Swift scripts (swift shebang), command-line tools

Create runnable Swift scripts with a shebang , read CommandLine.arguments , print help, and exit with proper status codes.

Swift scripts (swift shebang), command-line tools is a free Swift Academy lesson on CoddyKit — lesson 1 of 3. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, one of 3 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Why Swift scripts?

Swift can act as a scripting language. Use a shebang to run files directly, parse CommandLine.arguments, and exit with status codes for automation.

Shebang basics

Add #!/usr/bin/env swift as the first line, make the file executable, then run it like any shell script.

// First line (shebang) when saved to a file:
// #!/usr/bin/env swift
// Then mark file executable: chmod +x tool.swift
// Run directly: ./tool.swift

print("Hello from a Swift script!")

Arguments parsing

Use CommandLine.arguments to read inputs. Provide a short Usage message when required parameters are missing.

// Parse arguments: CommandLine.arguments[0] is the script path.
let args = CommandLine.arguments.dropFirst()  // ignore script name
if args.isEmpty {
    print("Usage: greet.swift <name>")
} else {
    let name = args[args.startIndex]
    print("Hello, \\(name)!")
}

Tiny options

Implement tiny flags without dependencies. Keep help clear: --help, --times N, --shout.

// Very small options parser: --shout and --times
struct Options {
    var shout = false
    var times = 1
    var rest: [String] = []
}

func parse(_ raw: ArraySlice<String>) -> Options {
    var o = Options()
    var it = raw.makeIterator()
    while let token = it.next() {
        switch token {
        case "--help", "-h":
            print("Usage: echo.swift [--shout] [--times N] <text>")
            exit(0)
        case "--shout":
            o.shout = true
        case "--times":
            if let nStr = it.next(), let n = Int(nStr), n > 0 { o.times = n }
        default:
            o.rest.append(token)
        }
    }
    return o
}

let options = parse(CommandLine.arguments.dropFirst())
let text = options.rest.joined(separator: " ").isEmpty ? "echo" : options.rest.joined(separator: " ")
let output = options.shout ? text.uppercased() : text
for _ in 0..<options.times { print(output) }

Exit status

Use exit(0) for success and non-zero for failures. Print errors to stderr for shell pipelines.

import Foundation

enum CLIError: Error { case invalidInput }

func validateNumber(_ s: String) throws -> Int {
    guard let n = Int(s) else { throw CLIError.invalidInput }
    return n
}

let args2 = CommandLine.arguments.dropFirst()
do {
    guard let first = args2.first else {
        print("Usage: num.swift <int>"); exit(64) // EX_USAGE
    }
    let n = try validateNumber(first)
    print("ok:", n)
    exit(0)
} catch {
    fputs("error: \\(error)\\n", stderr)
    exit(1)
}

Compile & distribute

For distribution, compile with swiftc to get a binary. For larger CLIs, move to SwiftPM and swift run.

// You can compile a single-file tool:
// swiftc tool.swift -o tool
// ./tool --help
print("Tip: use swiftc to build a tiny binary; for multi-file CLIs prefer SwiftPM (swift package init).")

Shebang purpose

Quick check: What does a shebang enable?

Recap

Recap: Add a shebang, read CommandLine.arguments, print Usage, and exit with proper codes. Compile with swiftc or move to SwiftPM for bigger tools.

Frequently asked questions

Is the “Swift scripts (swift shebang), command-line tools” lesson free?

Yes — the full text of “Swift scripts (swift shebang), command-line tools” is free to read here on the web, and the Swift Academy course includes 3 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Swift Academy course, upgrade to CoddyKit PRO.

What will I learn in “Swift scripts (swift shebang), command-line tools”?

Create runnable Swift scripts with a shebang , read CommandLine.arguments , print help, and exit with proper status codes. You practise Swift Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Swift Academy?

No prior experience is required. Swift Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 3, so you can start here or from the beginning and move at your own pace.

How long does the “Swift scripts (swift shebang), command-line tools” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Swift Academy lesson?

Yes. Every Swift Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Swift scripts (swift shebang), command-line tools
  2. C/Obj-C interop at a glance (no iOS specifics)
  3. Packaging binaries with SPM
← Back to Swift Academy