Golang : How to get own program name during runtime ?
One of the common question asked by newbie to Golang is how does one get their own program name during runtime. Getting the name right can be useful for task like checking how many processes with the same name already running in memory, passing additional arguments to own program depending on the Operating System Environment variables and many other reasons.
From Golang's http://golang.org/pkg/os/#pkg-variables. Args hold the command-line arguments, starting with the program name.
Therefore, to get the program name, use os.Args[0]
os.Args[0] // name of the command
os.Args1 // first command line parameter,
os.Args[2] // second command line parameter...
Example :
package main
import (
"os"
"fmt"
)
func main() {
fmt.Fprintf(os.Stderr, "your own program name is %s \n", os.Args[0])
}
$ go run myownprogramname.go
your own program name is /var/folders/52/tbjrbqsn6ysdrbqkx91tx6640000gn/T/go-build916658700/command-line-arguments/_obj/exe/myownprogramname
$ go build myownprogramname.go
$ ./myownprogramname
your own program name is ./myownprogramname
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+11.6k Golang : Handle API query by curl with Gorilla Queries example
+19.6k Golang : How to Set or Add Header http.ResponseWriter?
+6.1k Golang : How to verify input is rune?
+28.3k Golang : Connect to database (MySQL/MariaDB) server
+14.3k Golang : Convert IP version 6 address to integer or decimal number
+17.2k Golang : XML to JSON example
+16.5k Golang : Find out mime type from bytes in buffer
+13.2k Golang : Handle or parse date string with Z suffix(RFC3339) example
+5.6k Clean up Visual Studio For Mac installation failed disk full problem
+8.1k Findstr command the Grep equivalent for Windows
+13.4k CodeIgniter : "Fatal error: Cannot use object of type stdClass as array" message
+8.1k Golang : Handle Palindrome string with case sensitivity and unicode