Created
June 22, 2021 19:37
-
-
Save vguhesan/d1ea068b6e031ed1b8f02ef8fbace57f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"os" | |
"path/filepath" | |
) | |
func main() { | |
// Get Working Directory | |
path, err := os.Getwd() | |
if err != nil { | |
fmt.Println(err) | |
} | |
wdPath, _ := filepath.Abs(path) | |
fmt.Println("Working Directory........ " + wdPath) | |
binPath, _ := filepath.Abs(os.Args[0]) | |
fmt.Println("Binary Directory......... " + binPath) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For cases where you have a CLI binary and you're looking to update the binary-executable where the binary is installed and you may not have the path to that binary, then the above example comes in handy.
binPath represents the path to the binary executable whereas,
wdPath represents the path (present-working-directory) to where you are now.
binPath does not need to be necessarily the same as wdPath and you could also have the binary added to the $PATH (environment path)
-- Compiled the Golang binary with -o as "binarypath"
-- Moved "binarypath" binary to "_alt" folder
$ mv binarypath ../binarypath_alt
-- Invoked binarypath by specifying full path to binary
$ ../binarypath_alt/binarypath
Working Directory........ /Users/GoLangProjects/binarypath
Binary Directory......... /Users/GoLangProjects/binarypath_alt/binarypath
-- Prefixed _alt path to $PATH (system path)
-- Path before
$ echo $PATH
/Library/Frameworks/Python.framework/Versions/3.8/bin
$ export PATH=/Users/GoLangProjects/binarypath_alt/:$PATH
-- Path after change
$ echo $PATH
/Users/GoLangProjects/binarypath_alt/:/Library/Frameworks/Python.framework/Versions/3.8/bin:/
-- Executing binary from system-path
$ binarypath
Working Directory........ /Users/GoLangProjects/binarypath
Binary Directory......... /Users/GoLangProjects/binarypath/binarypath
Conclusion:
-- In a Linux system, os.Args[0] reflects the path to the binary executable.