46

What I am looking for here is the equivalent of C's argv[0].

The flag package only gives access to command line arguments, but not the executable name.

While one can get the process with Getpid(), I haven't found something that will give me access to the whole command line. The syscall command GetCommandLine() seems only to be available on Windows.

3 Answers 3

45

The traditional argv[0] in C is available in os.Args[0] in Go. The flags package simply processes the slice os.Args[1:]

Sign up to request clarification or add additional context in comments.

Comments

36

A better way as follows:

filename := filepath.Base(os.Args[0])

This will present only the application name and remove the path for you.

Comments

26

Since Go 1.8, the answer is os.Executable(). Similar to other languages, there is also os.Args[0]. One important distinction is that os.Executable() is guaranteed to return an absolute path.

1 Comment

Thanks. I hadn't noticed that. Most of the time I want os.Args[0], but it's useful to know about os.Executable().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.