Skip to content

os/exec: document that LookPath result may only be valid relative to current directory #3622

@alexbrainman

Description

@alexbrainman
This program should work, but fails

package main

import (
    "fmt"
    "log"
    "os"
    "os/exec"
    "path/filepath"
    "runtime"
)

func main() {
    var prog string
    if runtime.GOOS != "windows" {
        prog = "date"
        // add . at the front of our PATH,
        // windows starts search in the current directory anyway
        p := os.Getenv("PATH")
        err := os.Setenv("PATH", ".:"+p)
        if err != nil {
            log.Fatal(err)
        }
    } else {
        prog = "ipconfig"
    }
    // find our executable
    path, err := exec.LookPath(prog)
    if err != nil {
        log.Fatal(err)
    }
    dir, _ := filepath.Split(path)
    // chdir to where our executable lives
    err = os.Chdir(dir)
    if err != nil {
        log.Fatal(err)
    }
    // find our executable again
    path, err = exec.LookPath(prog)
    if err != nil {
        log.Fatal(err)
    }
    // run our executable with /tmp directory as current
    cmd := exec.Command(path)
    cmd.Dir = os.TempDir()
    out, err := cmd.CombinedOutput()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("out=%v\n", string(out))
}

I am not sure where things should be changed.

Alex

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions