I'm trying to execute a command in golang, which goes to ~ path. Like running ls ~
in terminal.
Eventually i'd like to create commands in specific directory, which is located on ~/TestDirectory, for example, git pull, mkdir, etc..
Here's what i've tried :
out, _ := exec.Command("ls", "~").Output()
-> Output is blank, so running exec.Command("cd", "~")
doesn't go to ~ directory.out, _ := exec.Command("ls", "../..").Output()
-> Output is 2 directories above my current, but its not the way to do it since the current project might be anywhereAlso, i've tried setting the current directory of the command, the output was nil.
cmd := exec.Command("cd")
cmd.Dir = "~"
cmd.Run()
The ~
is expanded by your shell (to your $HOME
, at least on POSIX systems; read about globbing and glob(7)). You could use os.GetEnv("HOME")
to get its expansion
Also, i've tried setting the current directory of the command, the output was nil.
Each process has its own working directory. But exec.Command
is running a new process, so in your case only that process (not your own one) is changing its working directory. You want to use os.Chdir
to change the working directory of your own process.