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
+4.9k Facebook : How to force facebook to scrape latest URL link data?
+7.9k Golang : Intercept and compare HTTP response code example
+7k Golang : Randomize letters from a string example
+3.8k Linux/MacOSX : How to symlink a file?
+15.7k Golang : Get number of CPU cores
+13.5k Golang : Accurate and reliable decimal calculations
+21.1k Golang : How to read JPG(JPEG), GIF and PNG files ?
+5.5k Golang : Embedded or data bundling example
+9.4k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+3.5k Javascript : Detect when console is activated and do something about it
+26k Golang : Convert integer to binary, octal, hexadecimal and back to integer
+5.6k Golang : Derive cryptographic key from passwords with Argon2