douya2982 2017-05-14 04:09
浏览 268
已采纳

直接运行bash命令和通过exec.Command运行结果不同

On Linux OS, run "realpath ~/bin" gives the correct path "/home/user1/bin".

But when I run it as bellow:

cmd := exec.Command("realpath", "~/bin")
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
    panic(err)
}
fmt.Println("Realapth:", out.String())

I got panic: exit status 1.

BTW: with command as below:

cmd := exec.Command("realpath", "--help")

I can get correct help message for realpath command. I think that means it is really in my executable path.

  • 写回答

1条回答 默认 最新

  • dtl4521 2017-05-14 05:04
    关注

    If you run the command in a shell (e.g. bash), a tilde-prefix is expanded by the shell before being passed to realpath.

    However if you run it in a go application, tilde is left as is and realpath assumes it as a part of the path name. To see the difference, you can try the following command in shell (Linux OS):

    //1. correctly expanded
    realpath './bin'
    
    //2. tilde not expanded
    realpath '~/bin'
    
    //3. tilde expansion
    realpath ~/bin
    

    The (2) should failed, and the situation in your go application is similar to this. To verify, change your go code as follows:

    cmd := exec.Command("realpath", "~/bin")
    var out bytes.Buffer
    var serr bytes.Buffer
    cmd.Stdout = &out
    cmd.Stderr = &serr
    err := cmd.Run()
    if err != nil {
        fmt.Printf("Error = %v, %v
    ", err, serr.String())
        panic(err)
    }
    fmt.Println("Realapth:", out.String())
    

    You should be able to observe error message produced by realpath command.

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

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器