0
0
GoHow-ToBeginner · 3 min read

How to Use os.Args in Go for Command Line Arguments

In Go, os.Args is a slice of strings that holds the command line arguments passed to your program. The first element os.Args[0] is the program name, and the following elements are the arguments. You can access and use these arguments to customize your program's behavior.
📐

Syntax

os.Args is a slice of strings ([]string) from the os package. It contains all command line arguments including the program name at index 0.

  • os.Args[0]: The name or path of the running program.
  • os.Args[1:]: The actual arguments passed to the program.
go
import "os"

func main() {
    args := os.Args
    // args[0] is program name
    // args[1:] are command line arguments
}
💻

Example

This example prints the program name and all command line arguments passed to it.

go
package main

import (
    "fmt"
    "os"
)

func main() {
    fmt.Println("Program name:", os.Args[0])
    fmt.Println("Arguments:")
    for i, arg := range os.Args[1:] {
        fmt.Printf("Argument %d: %s\n", i+1, arg)
    }
}
Output
Program name: ./myprogram Arguments: Argument 1: hello Argument 2: world
⚠️

Common Pitfalls

Common mistakes when using os.Args include:

  • Not checking if enough arguments are provided before accessing them, which causes runtime errors.
  • Confusing os.Args[0] (program name) with actual arguments.
  • Assuming arguments are always strings without conversion when needed.

Always check the length of os.Args before using arguments.

go
package main

import (
    "fmt"
    "os"
)

func main() {
    // Wrong: Accessing argument without checking length
    // fmt.Println(os.Args[1]) // May panic if no argument

    // Right: Check length first
    if len(os.Args) < 2 {
        fmt.Println("Please provide at least one argument.")
        return
    }
    fmt.Println("First argument:", os.Args[1])
}
Output
Please provide at least one argument.
📊

Quick Reference

TermDescription
os.ArgsSlice of strings with all command line arguments
os.Args[0]Program name or path
os.Args[1:]Actual command line arguments
len(os.Args)Number of arguments including program name
Check lengthAlways verify length before accessing arguments

Key Takeaways

Use os.Args to access command line arguments as a slice of strings.
os.Args[0] is the program name; actual arguments start from os.Args[1].
Always check the length of os.Args before accessing arguments to avoid errors.
Arguments are strings; convert them if you need other types.
Use a loop to process multiple arguments easily.