Golang : Get absolute path to binary for os.Exec function with exec.LookPath
Sometimes it is good to tell our Golang program to execute exactly which binary file based on the path. For instance, there will be situation where due to poor system administration on client's machine....possible...duplicate binaries might caused unwanted/weird result due to different versions.
Before we can execute a binary with os.Exec()
, Go needs to know the absolute path to the binary. This can be accomplish with the exec.LookPath()
function.
If the path returned by exec.LookPath()
function is not what you after, then you want to change the path variable before executing.
For example :
package main
import (
"fmt"
"os/exec"
)
func main() {
path, err := exec.LookPath("dig")
if err != nil {
panic(err)
}
fmt.Println("Will be executing the binary at :", path)
// if path is not what you after, assign new string value to path
cmd := exec.Command(path, "any", "google.com")
out, err := cmd.Output()
if err != nil {
fmt.Println(err.Error())
return
}
fmt.Print(string(out))
}
Sample output :
Will be executing the binary at : /usr/bin/dig
Reference :
See also : Golang : Execute shell command
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
+9.7k Golang : Create Temporary File
+29.2k Golang : Interpolating or substituting variables in string examples
+22.1k Golang : Fix type interface{} has no field or no methods and type assertions example
+7.9k Golang : io.Reader causing panic: runtime error: invalid memory address or nil pointer dereference
+10.7k Golang : Perform sanity checks on filename example
+8.6k Golang : Turn string or text file into slice example
+19.1k Golang : How to force compile or remove object files first before rebuild?
+3.8k Golang : Experimental Jawi programming language
+32.6k Golang : Proper way to set function argument default value
+6.4k Golang : Create zip/ePub file without compression(use Store algorithm)
+35k Golang : Display float in 2 decimal points and rounding up or down
+18.2k Golang : Convert seconds to human readable time format example