duanjieyi6582 2018-08-18 09:04
浏览 46
已采纳

转到〜(波浪号字符)目录路径

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 :

  1. out, _ := exec.Command("ls", "~").Output() -> Output is blank, so running exec.Command("cd", "~") doesn't go to ~ directory.
  2. 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 anywhere
  3. Also, i've tried setting the current directory of the command, the output was nil.

    cmd := exec.Command("cd")
    cmd.Dir = "~"
    cmd.Run()
    
  • 写回答

1条回答 默认 最新

  • douer9399 2018-08-18 09:14
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?