Command Line Arguments in OpenSCAD

Command-line arguments are a common way to parameterize execution of programs. For example, openscad my_model.scad -o output.stl uses my_model.scad and -o output.stl arguments to the openscad program.

// OpenSCAD doesn't have a direct equivalent to command-line arguments
// However, we can use the built-in special variables to demonstrate similar functionality

// The $0 variable contains the name of the currently processed file
echo("Script name:", $0);

// The $user_variables array contains all variables defined on the command line
echo("Command line variables:", $user_variables);

// You can access individual command line variables like this:
if (len($user_variables) > 0) {
    echo("First command line variable:", $user_variables[0]);
}

// We can also define our own variables that can be set from the command line
variable1 = 10; // This can be overridden from the command line
echo("variable1:", variable1);

// In OpenSCAD, we typically use these variables to parameterize our models
cube([variable1, 20, 30]);

To experiment with command-line arguments in OpenSCAD, you can run the script from the command line:

$ openscad -D "variable1=15" my_script.scad -o output.stl

This will set variable1 to 15 and output the result to output.stl.

OpenSCAD doesn’t provide direct access to raw command-line arguments like some other languages. Instead, it uses a system of special variables and command-line defined variables to achieve similar functionality.

The $0 variable provides the name of the current script, similar to how other languages might provide the program name as the first argument.

The $user_variables array contains all variables defined on the command line, which you can iterate over or access individually.

Custom variables like variable1 can be defined in the script and optionally overridden from the command line, allowing for parameterization of your models.

Next, we’ll look at more advanced ways to parameterize OpenSCAD models using modules and functions.