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

直接运行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.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题