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 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划