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.

Lesson 1 of 38 steps

Swift scripts (swift shebang), command-line tools is a free Swift Academy lesson on CoddyKit. This is lesson 1 of 3. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Swift Academy learning path, and your progress syncs across the web and the CoddyKit app. The Swift Academy course includes 3 lessons in total.

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.

Free to start

Learn Swift with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
122
Lessons
409

Frequently Asked Questions

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

Yes — any 3 lessons of the Swift Academy learning path, including “Swift scripts (swift shebang), command-line tools”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Swift Academy course includes 3 lessons in total.

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, so you can start here or from the beginning and move at your own pace. This is lesson 1 of 3.

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