← Back to Go Course | Chapter 13: File IO & OS | Lesson 1 of 7

The os Package

The os package is Go's connection to the operating system itself -- it's how a program reads command-line input, looks at environment settings, and talks to files.

What the os Package Provides

The os package is Go's gateway to the underlying operating system: reading and writing files, inspecting environment variables, accessing command-line arguments, and controlling process exit codes.

Example: What the os Package Provides

markup
package main

import (
	"fmt"
	"os"
)

func main() {
	fmt.Println("program name:", os.Args[0])
}

Exiting with a Status Code

os.Exit(code) immediately terminates the program with the given exit status, useful for signaling success (0) or failure (non-zero) to whatever launched the program -- but unlike a normal return, it skips any pending deferred calls.

Note: Because os.Exit skips defers, prefer letting main() return normally when cleanup matters.

Example: Exiting with a Status Code

markup
package main

import (
	"fmt"
	"os"
)

func main() {
	fmt.Println("about to check a condition")
	ok := true
	if !ok {
		os.Exit(1)
	}
	fmt.Println("condition passed, continuing normally")
}

Getting the Current Working Directory

os.Getwd returns the directory the program is currently running from, along with an error if it couldn't be determined -- useful for building file paths relative to where the program was launched.

Example: Getting the Current Working Directory

markup
package main

import (
	"fmt"
	"os"
)

func main() {
	dir, err := os.Getwd()
	if err != nil {
		fmt.Println("error:", err)
		return
	}
	fmt.Println("running from a directory (path length):", len(dir))
}
Common Mistakes
  1. Forgetting to check the error returned by most os functions, since many operations (opening a file, reading a variable) can fail.
  2. Confusing os.Args[0] (the program name) with the first real command-line argument, which is actually os.Args[1].
  3. Calling os.Exit() inside code with pending defers, which skips them entirely -- os.Exit does not run deferred functions.
Chapter Summary
  • The os package provides access to OS-level features: files, environment variables, command-line arguments, and process control.
  • os.Args holds the program's command-line arguments, with os.Args[0] being the program name itself.
  • os.Exit(code) terminates the program immediately, skipping any deferred function calls.
  • Most os functions that touch the outside world return an error that should always be checked.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.