Nyx by Example

Shebang Script

Nyx scripts can be run directly from the command line using a shebang line (#!/usr/bin/env nyx). The compiler's lexer recognizes #! at the start of a file and skips the entire line as a comment. get_args() provides access to command-line arguments.

Code

#!/usr/bin/env nyx
// Shebang scripts — running Nyx files as executable scripts
// Scripts shebang — ejecutar archivos Nyx como scripts ejecutables
//
// Make this file executable: chmod +x 70-shebang-script.nx
// Then run directly: ./70-shebang-script.nx

fn greet(name: String) -> String {
    return "Hello, " + name + "!"
}

fn main() -> int {
    print(greet("World"))
    print("running as a script")

    // Access command-line arguments
    let args: Array = get_args()
    print("args: " + int_to_string(args.length()))

    if args.length() > 1 {
        let name: String = args[1]
        print(greet(name))
    }

    return 0
}

Output

Hello, World!
running as a script
args: 1

Explanation

A shebang line (#!/usr/bin/env nyx) at the top of a .nx file tells the OS to run it with the nyx command. The compiler's lexer recognizes #! at the start of a token and skips the entire line as a comment, so the shebang does not interfere with compilation.

get_args() returns the command-line arguments as an array of strings. The first element (args[0]) is the program name. Any additional arguments are accessible by index.

To make a script executable: create the file with the shebang line, run chmod +x script.nx, then execute it directly with ./script.nx. This makes Nyx suitable for shell scripting, build scripts, and quick utilities.

← Previous Next →

Source: examples/by-example/70-shebang-script.nx