1

I am trying to make my shell cd into a directory. Is there a better way to do this? The only problem with this way is that my shell is a subprocess of the current shell. Making me have to exit twice.

package main

func main(){
  err = syscall.Chdir(os.Getenv("HOME") + "/dev")
  exitIfErr(err)
  err = syscall.Exec(os.Getenv("SHELL"), []string{""}, os.Environ())
  exitIfErr(err)
}
Jason Waldrip
  • 5,038
  • 8
  • 36
  • 59
  • Another issue you might encounter is that the `SHELL` environment variable is not available on Windows. – kichik Oct 24 '14 at 05:03
  • Wait. But don't you want to exec from your shell, to replace the outer shell process with your Go process? http://stackoverflow.com/questions/18351198/what-is-the-use-of-exec-command-in-the-shell-scripting – dyoo Oct 24 '14 at 06:15
  • @dyoo you are right. I just want to tell my outer shell process to change directories. So how do I go about that? – Jason Waldrip Oct 24 '14 at 13:30
  • 1
    I don't think what you're asking for, to directly mutate the parent process from a child process, is doable. Offhand, that would break process isolation. http://stackoverflow.com/questions/9360679/can-the-child-process-affect-parent-process-environment The best I can think of at the moment is _replacing_ the parent shell process with your Go program via a shell exec, and the Go program _replacing_ its process with the new shell process via the `Exec` call you're doing at the moment. But if you're going to go through all that trouble, why not just `cd` from your parent shell process? – dyoo Oct 24 '14 at 22:26

1 Answers1

2

You could use os.Chdir instead to change directories:

func Chdir(dir string) error

Chdir changes the current working directory to the named directory. If there is an error, it will be of type *PathError.

Regarding the exec I'd recommend using the os/exec package to run your sub-process. It sorts out all kind of portability nuances between *nix systems and even windows as far as applicable.

thwd
  • 23,956
  • 8
  • 74
  • 108