Skip to Content
Course content

118: os.Args and Command-Line Arguments

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've seen this specific bug more times than I can count when developers start building their first CLI tools in Go. You're trying to pass a filename or a configuration path into your program, but for some reason, the program keeps trying to "open" its own binary file instead of the file you actually typed in the terminal.

package main

import (
	"fmt"
	"os"
)

func main() {
	// We want to print the name of the file the user wants to process
	fileName := os.Args[0]
	fmt.Printf("Processing file: %s\n", fileName)
	
	// Imagine some logic here to open and read the file...
}

If you run this with go run main.go data.txt, you'll see it prints something like Processing file: /tmp/go-build.../exe/main. It completely ignored data.txt. It's frustrating because the code looks logically sound—you're grabbing the first thing in the arguments list, right?

Why your program is trying to open itself

The "gotcha" here is that os.Args isn't just a list of the arguments you passed to the program. It's a slice of strings where the very first element—index 0—is always the path to the program that is currently running. Whether you're using go run or running a compiled binary, the operating system always puts the executable's name at the front of the line.

So, if you run mytool input.txt output.txt, the os.Args slice actually looks like this:

  • os.Args[0]: "mytool"
  • os.Args[1]: "input.txt"
  • os.Args[2]: "output.txt"

Indexing from one and guarding against panics

To fix this, you need to start looking at index 1. But there's a second trap: if you try to access os.Args[1] and the user didn't provide any arguments, your program will panic with an index out of range error. I hate it when my tools just crash without telling me why, so we should always check the length of the slice first.

package main

import (
	"fmt"
	"os"
)

func main() {
	// Check if the user actually provided the required argument
	if len(os.Args) < 2 {
		fmt.Println("Usage: go run main.go [filename]")
		os.Exit(1) // Exit with an error code
	}

	// Index 0 is the program name, index 1 is the first real argument
	fileName := os.Args[1]
	fmt.Printf("Processing file: %s\n", fileName)
}

Now the program behaves. It checks if there's enough data to proceed, provides a helpful usage message if not, and correctly identifies the user's input. If you need all the arguments minus the program name, a clean way to do that is by slicing the slice: args := os.Args[1:]. This gives you a new slice containing only the actual inputs.

As your tools get more complex—say, you need -v for verbose mode or -port 8080—you'll likely move over to the flag package. But os.Args is the raw, honest foundation of how Go sees the command line. It's fast, it's simple, and once you remember that index 0 is "the boss," it's very reliable.




📋 Practical Task

Build a Simple File Word Counter

Create a Go program that accepts a filename as a command-line argument. The program should:

  • Check if a filename was provided via os.Args. If not, print a usage message (e.g., "Please provide a filename") and exit the program.
  • Read the content of the provided file (you can use os.ReadFile).
  • Count the number of words in that file (hint: strings.Fields is very helpful here).
  • Print the total word count to the console.

Test your tool: Run it once without any arguments to ensure it doesn't panic, and then run it again with a path to a real .txt file to verify the count.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.