MCPcopy Create free account
hub / github.com/Sma1lboy/RegTool / SetEnvVarToFile

Function SetEnvVarToFile

shell/utils.go:12–51  ·  view source on GitHub ↗

SetEnvVarToFile writes the environment variable to the specified shell configuration file.

(filename, key, value string)

Source from the content-addressed store, hash-verified

10
11// SetEnvVarToFile writes the environment variable to the specified shell configuration file.
12func SetEnvVarToFile(filename, key, value string) error {
13 usr, err := user.Current()
14 if err != nil {
15 return fmt.Errorf("error getting current user: %w", err)
16 }
17 homeDir := usr.HomeDir
18 filePath := fmt.Sprintf("%s/%s", homeDir, filename)
19
20 input, err := os.ReadFile(filePath)
21 if err != nil {
22 if os.IsNotExist(err) {
23 file, err := os.Create(filePath)
24 if err != nil {
25 return err
26 }
27 defer file.Close()
28 } else {
29 return err
30 }
31 }
32
33 lines := strings.Split(string(input), "\n")
34 var output []string
35 var found bool
36
37 for _, line := range lines {
38 if strings.HasPrefix(line, fmt.Sprintf("export %s=", key)) {
39 output = append(output, fmt.Sprintf("export %s=\"%s\"", key, value))
40 found = true
41 } else {
42 output = append(output, line)
43 }
44 }
45
46 if !found {
47 output = append(output, fmt.Sprintf("export %s=\"%s\"", key, value))
48 }
49
50 return os.WriteFile(filePath, []byte(strings.Join(output, "\n")), 0644)
51}
52
53// GetEnvVarFromFile reads the environment variable from the specified shell configuration file.
54func GetEnvVarFromFile(filename, key string) (string, error) {

Callers 2

SetEnvMethod · 0.92
SetEnvMethod · 0.92

Calls

no outgoing calls

Tested by

no test coverage detected