The built-in os module is the bridge between a program and the operating system around it.

It lets a script read and change its environment variables, run other programs, and perform the few file system operations that are not about contents of files: moving, deleting and creating. Like any standard module, it is brought in with import:

import os

The module is deliberately small.

Reading and writing the contents of files, and talking to other programs though pipes, belongs to the IO module, and the module is meant to be used together with it. An embedding application, as seen in Part III, may also choose to not provide os at all, since a script that can run commands and delete arbitrary files has no place in a sandbox.

Environment Variables

Every process has an environment, a set of named strings that it inherits from the program that started it, and passes on to the programs that it starts. The function os.getenv reads one variable by name, and returns nil when it is not set:

var home = os.getenv("HOME")
print(home)     // /home/tea, or nil if there is none

An optional second argument, which must also be a string, is returned instead of nil, which avoids the usual test:

var editor = os.getenv("EDITOR", "vi")

The function os.setenv sets a variable, creating it if necessary.

Passing nil as the value removes the variable instead. Anything else is an error, and so is a failure of the system to apply the change:

os.setenv("TEA_MODE", "debug")
print(os.getenv("TEA_MODE"))    // debug

os.setenv("TEA_MODE", nil)
print(os.getenv("TEA_MODE"))    // nil

Changes made this way affect the running program and every program that is starts afterwards. They are never visible to the program that launched it, nor to the shell you typed the command in.

The env Map

The attribute os.env is a map holding the whole environment, with the names of the variables as keys. It is convenient for looking at everything at once:

for var name in os.env.keys.sort((a, b) => a < b)
{
    print("${name}=${os.env[name]}")
}

The map, however, is a snapshot, taken at the moment the module is first imported, and it is not connected to the real environment in any way. Changing the map does not change the environment, and a later call to os.setenv does not update the map. To read the current value of a variable, always use os.getenv; use os.env only for what was there when the program first started.

Since it is an ordinary map, reading a name that is not present with a subscript raises an error, as for any other map. When the variable might be missing, use get, or simply os.getenv:

print(os.env.get("USER", "nobody"))

Running Commands

The function os.execute runs a command through the system shell, waits for it to finish, and returns a number describing how it ended:

var status = os.execute("echo hello")   // hello
print(status)                           // 0

The command inherits the standard streams of the program, so whatever it prints goes straight to the terminal, and it is not available to the script.

A status of 0 means that the command succeeded. Any other number means that it failed, but the exact meaning of such a number is left to the platform and to the shell, so a script should rarely do more than compare it with zero.

Since a program that needs to read the output of a command cannot do it with os.execute, that is the job of io.popen, described in the previous chapter.

There are two things to keep in mind.

First, the text is handed to the shell as it is, so a command built from outside data, such as a file name typed by a user, can contain anything, including more commands. Never assemble a command from input that you do not control.

Second, the command is written in the language of the shell of the platform. Something as simple as listing a directory is ls on one system, and dir on another, so portable scripts keep to commands that exist everywhere, or choose one depending on the platform, as shown at the end of this chapter.

When a script writes text to standard output and runs a command right after, the two can appear in the wrong order, because what a program writes may wait in a buffer. Calling io.stdout.flush() before os.execute makes sure that everything written so far is out first.

Files and Directories

Three functions manage files and directories.

The function os.rename renames or moves a file, and os.remove deletes one. Both return a boolean telling whether the operation actually worked, instead of raising an error:

if os.rename("draft.txt", "final.txt")
{
    print("renamed")
}

if not os.remove("old.log")
{
    print("old.log could not be removed")
}

Failure is common and expected here, for example because the file does not exist, so the result is meant to be tested.

Note that it does not say why the operation failed. What happens when the destination of a rename already exists is also up to the platform; most systems replace it, while others refuse it. Also, os.remove is meant for files; whether it also removes empty directories depends on the system.

The function os.mkdir creates a directory.

It differs from the previous two, since it raises an error when the directory cannot be created, which includes the case where is already exists:

os.mkdir("output")

This difference is a good example of the choice discussed in the chapter on error handling.

When the directory is not expected to be there already, a failure is a real problem and the error is what we want. When it may well exist, the error can be ignored with a protected call:

pcall(os.mkdir, "output")

Only one level is created at a time, so the parent of the new directory must already exist.

On systems that have file permissions, the new directory is created with the most permissive ones, as restricted by the settings of the user.

The Platform

Two attributes describe where the program is running.

os.name is a simple string naming the operating system, and os.arch one naming the processor architecture. Their main use is to choose between alternatives:

print(os.name, os.arch)

The exact strings are those of the interpreter that is running the program, so the simplest way to learn the ones you need is to print them on the platforms you care about, and to compare against those values.

An Example

The following program writes a report in a directory, taking its name from an environment variable, with a default.

It writes the file under a temporary name and then renames it to the final one, a common precaution; a program that reads the report never finds it half written, because on most systems a rename is completed in a single step. Finally, it runs a command to announce the result.

// report.tea
import io, os

var dir = os.getenv("REPORT_DIR", "out")
var path = dir + "/report.txt"
var temp = path + ".tmp"

// the directory may already exist, which is not a problem
pcall(os.mkdir, dir)

var f = io.open(temp, "w")
f.write("generated report\n")
f.close()

if not os.rename(temp, path)
{
    error("cannot move ${temp} to ${path}")
}
print("written ${path}")

io.stdout.flush()
if os.execute("echo done") != 0
{
    print("the announcement failed")
}
$ tea report.txt
written out/report.txt
done

Run it twice, or set REPORT_DIR to another name, and it behaves correctly each time.

The directory is created only if needed, thanks to pcall; the failure of rename is a value to check, and becomes an error only because the program decides that it cannot go on; and the flush guarantees that the line from print appears before the output of the command.