Nyx by Example

Environment Variables

Nyx exposes the process environment through two built-in functions: getenv returns a variable's value or an empty string if it is not set, while getenv_default lets you supply a fallback value, making configuration code safer and more readable.

Code

// Variables de entorno: getenv(), getenv_default()

fn main() -> int {
    // getenv retorna el valor o "" si no existe
    let home: String = getenv("HOME")
    print("HOME=" + home)

    let path: String = getenv("PATH")
    // Mostrar solo los primeros 40 chars para no saturar la salida
    if path.length() > 40 {
        print("PATH=" + path.substring(0, 40) + "...")
    } else {
        print("PATH=" + path)
    }

    // getenv_default: retorna el segundo argumento si la variable no existe
    let mi_var: String = getenv_default("MI_VAR_NX", "valor_por_defecto")
    print("MI_VAR_NX=" + mi_var)

    let usuario: String = getenv_default("USER", "desconocido")
    print("USER=" + usuario)

    return 0
}

Output

HOME=/home/alice
PATH=/usr/local/bin:/usr/bin:/bin...
MI_VAR_NX=valor_por_defecto
USER=alice

Explanation

getenv(name) wraps the POSIX getenv(3) call and converts the result to a Nyx String. If the variable is not set in the process environment, it returns an empty string "" rather than crashing — this makes it safe to call unconditionally.

getenv_default(name, fallback) is a convenience wrapper that returns the variable's value when it exists, or fallback otherwise. This pattern is common in twelve-factor applications where every configuration value should have a documented default.

The PATH variable is often very long, so the example trims it to 40 characters using .substring(0, 40) to keep the output readable. The .length() check before slicing avoids an out-of-bounds error when PATH happens to be shorter than expected.

← Previous Next →

Source: examples/by-example/14-env-vars.nx