The os Package
In this page:
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
package main
import (
"fmt"
"os"
)
func main() {
fmt.Println("program name:", os.Args[0])
}
Login to try C/C++/Java/PHP code in the editor
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
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")
}
Login to try C/C++/Java/PHP code in the editor
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
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))
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting to check the error returned by most os functions, since many operations (opening a file, reading a variable) can fail.
- Confusing os.Args[0] (the program name) with the first real command-line argument, which is actually os.Args[1].
- Calling os.Exit() inside code with pending defers, which skips them entirely -- os.Exit does not run deferred functions.
- 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: