codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🐹

Go (Golang)

34 / 72 topics
27Standard Library Overview28IO Package29Net Package30HTTP Package31JSON Package32XML Package33Time Package34OS Package35Fmt Package36Math Package37Regexp Package38Log Package39Flag Package40Context Package41Embed Package
Tutorials/Go (Golang)/OS Package
🐹Go (Golang)

OS Package

Updated 2026-04-20
2 min read

OS Package

The os package in Go is a fundamental part of the standard library, providing a platform-independent interface for interacting with the operating system. This tutorial will cover various aspects of the os package, including file operations, environment variables, process management, and more.

Introduction to the OS Package

The os package provides functions and types that are essential for working with the operating system. It includes functionalities such as reading from and writing to files, managing environment variables, executing external commands, and handling signals.

To use the os package in your Go programs, you need to import it:

import "os"

File Operations

Opening Files

The os.Open function is used to open a file for reading. It returns a *os.File object and an error if any occurs.

file, err := os.Open("example.txt")
if err != nil {
    log.Fatal(err)
}
defer file.Close()

Creating Files

To create or truncate a file, use the os.Create function:

file, err := os.Create("newfile.txt")
if err != nil {
    log.Fatal(err)
}
defer file.Close()

Writing to Files

The WriteString method of the *os.File object can be used to write strings to a file:

_, err = file.WriteString("Hello, world!")
if err != nil {
    log.Fatal(err)
}

Reading from Files

To read from a file, use the Read or ReadString methods:

data := make([]byte, 100)
n, err := file.Read(data)
if err != nil && err != io.EOF {
    log.Fatal(err)
}
fmt.Printf("Read %d bytes: %s\n", n, data[:n])

File Permissions

You can set file permissions using the os.Chmod function:

err = os.Chmod("example.txt", 0644)
if err != nil {
    log.Fatal(err)
}

Environment Variables

The os package provides functions to interact with environment variables.

Getting an Environment Variable

Use os.Getenv to retrieve the value of an environment variable:

value := os.Getenv("PATH")
fmt.Println("PATH:", value)

Setting an Environment Variable

To set an environment variable, use os.Setenv:

err = os.Setenv("MY_VAR", "my_value")
if err != nil {
    log.Fatal(err)
}

Process Management

The os package also includes functions for managing processes.

Executing Commands

Use the exec.Command function to execute external commands:

cmd := exec.Command("ls", "-l")
output, err := cmd.Output()
if err != nil {
    log.Fatal(err)
}
fmt.Println(string(output))

Exiting a Program

To terminate a program, use os.Exit:

os.Exit(0) // 0 indicates successful termination

Signal Handling

Go provides a way to handle signals using the os package.

Receiving Signals

Use signal.Notify to receive signals:

done := make(chan os.Signal, 1)
signal.Notify(done, os.Interrupt, syscall.SIGTERM)

select {
case <-done:
    fmt.Println("Received signal, exiting...")
}

Best Practices

  • Error Handling: Always check for errors returned by os functions. Use log.Fatal or similar functions to handle critical errors.
  • Resource Management: Use defer to ensure that resources like files and network connections are properly closed after use.
  • Security: Be cautious when handling environment variables, especially sensitive ones. Avoid hardcoding sensitive information in your code.

Conclusion

The os package is a powerful tool for interacting with the operating system in Go. By understanding its capabilities, you can build robust applications that manage files, processes, and more effectively. This tutorial has covered the basics of file operations, environment variables, process management, and signal handling using the os package.

For further exploration, consider reading the official documentation for detailed information on all available functions and types in the os package.


PreviousTime PackageNext Fmt Package

Recommended Gear

Time PackageFmt Package