在新目录中打开Shell

huangapple go评论69阅读模式
英文:

Opening Shell in New Directory

问题

我正在尝试让我的shell进入一个目录。有没有更好的方法来做这个?这种方法的唯一问题是我的shell是当前shell的子进程,这使得我必须退出两次。

package main

func main() {
    err := syscall.Chdir(os.Getenv("HOME") + "/dev")
    exitIfErr(err)
    err = syscall.Exec(os.Getenv("SHELL"), []string{""}, os.Environ())
    exitIfErr(err)
}

你可以尝试使用os.Chdir函数来改变当前工作目录,而不是使用syscall.Chdir。这样你就不需要启动一个新的子进程来执行命令了。以下是修改后的代码:

package main

import (
    "os"
    "os/exec"
)

func main() {
    err := os.Chdir(os.Getenv("HOME") + "/dev")
    exitIfErr(err)
    cmd := exec.Command(os.Getenv("SHELL"))
    cmd.Stdin = os.Stdin
    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stderr
    err = cmd.Run()
    exitIfErr(err)
}

这样修改后,你的shell将直接切换到指定目录,并在同一个进程中执行新的shell。

英文:

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)
}

答案1

得分: 2

你可以使用os.Chdir来改变目录:

func Chdir(dir string) error

> Chdir函数将当前工作目录更改为指定的目录。如果出现错误,错误类型将为*PathError

关于exec,我建议使用os/exec包来运行子进程。它可以处理*nix系统和Windows之间的各种可移植性细节。

英文:

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.

huangapple
  • 本文由 发表于 2014年10月24日 12:48:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/26541666.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定