os/exec run command with changed directory

7,922 views
Skip to first unread message

Andy R

unread,
Sep 2, 2013, 9:57:45 AM9/2/13
to golan...@googlegroups.com
Hi *,

I'd like to run a script in a subdirectory and also have the working directory for it there.

These are the snippets I tried:

1.)
//fork/exec hooks/script.sh: no such file or directory
cmd := exec.Command("hooks/script.sh")
cmd.Dir = "hooks"
2.)
//exec: "script.sh": executable file not found in $PATH
cmd := exec.Command("script.sh")
cmd.Dir = "hooks"

3.)
// Working:
cmd := exec.Command("hooks/script.sh")
cmd.Dir = "hooks"
cmd.Path = "script.sh"
cmd.Args[0] = "script.sh"

4.)
// Working
cmd := exec.Cmd{
  Path: "script.sh"
  Args: []string{"script.sh"},
  Dir: "hooks",
}

5.)
// Working
absexe, _ := filepath.Abs("hooks/script.sh")
cmd := exec.Command(absexe)
cmd.Dir = "hooks"


Now I understand that 1) shouldn't work. But I would've expected 2) to work. However in:
it seems like the error is set upon calling Command and sticks around even though I'm setting Dir later on.

Is this the intended behavior? Shouldn't the LookPath() call in Command() maybe happen later and take Dir into account?

Cheers,
Andy


Mitchell Hashimoto

unread,
Sep 3, 2013, 2:39:19 AM9/3/13
to golan...@googlegroups.com
Andy,

LookPath uses the PATH environmental variable to look up the location of an executable. The "Path" member of the "Cmd" struct has no effect whatsoever on it. Even if PATH contained ".", the LookPath happens within the cwd of the running process, not the cwd of the future subprocess, so it would not find it.

As far as I can tell, this is all working as intended.

Best,
Mitchell

Carlos Castillo

unread,
Sep 3, 2013, 10:32:35 AM9/3/13
to golan...@googlegroups.com
You can use os.Chdir (http://golang.org/pkg/os/#Chdir) to change the current working directory. To see the current directory use os.Getwd (http://golang.org/pkg/os/#Getwd).

Use these before you run exec.Command().


On Monday, September 2, 2013 6:57:45 AM UTC-7, Andy R wrote:
Reply all
Reply to author
Forward
0 new messages