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
+18.4k Golang : Example for RSA package functions
+18.6k Golang : convert int to string
+20.5k Android Studio : AlertDialog and EditText to get user string input example
+6k Golang : Missing Subversion command
+6k Fontello : How to load and use fonts?
+8.5k Golang : Add text to image and get OpenCV's X, Y co-ordinates example
+16.3k Golang : Find out mime type from bytes in buffer
+18.6k Golang : Iterating Elements Over A List
+6.3k Unix/Linux : Use netstat to find out IP addresses served by your website server
+19.3k Golang : How to count the number of repeated characters in a string?
+35.2k Golang : Smarter Error Handling with strings.Contains()
+15.2k Golang : How to get Unix file descriptor for console and file