go linux 命令执行问题

5kill · 2017-07-25 06:17:41 · 2210 次点击 · 大约8小时之前 开始浏览    置顶
这是一个创建于 2017-07-25 06:17:41 的主题,其中的信息可能已经有所发展或是发生改变。

新手求教 想用go去linux下 执行一些linux 系统命令获得结果,没有用shell编程,但是go 不能执行history top 这样命令 有人也遇到过这样问题么 附上代码方便大家测试

package main 

import (
"fmt"
"os/exec"
)

//换做 'ls' 这样名领是可以的

func getHistory(){
    cmd := exec.Command("/bin/bash","-c","history")
    out,err := cmd.Output()
    if err != nil{
        fmt.Println(err)
    }
    fmt.Println(string(out))

}    




func main() {
    getHistory()
}

有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

2210 次点击  
加入收藏 微博
6 回复  |  直到 2017-07-25 08:40:03
channel
channel · #1 · 8年之前

history 不是一个 linux 命令,而是 bash 内部的一个命令吧。top 因为是交互式的?

5kill
5kill · #2 · 8年之前
channelchannel #1 回复

history 不是一个 linux 命令,而是 bash 内部的一个命令吧。top 因为是交互式的?

对,所以要执行 history这样 内部命令 不能用这样方式么? top 确实是动态的 有木有linux 命令的操作方式呢。

5kill
5kill · #3 · 8年之前
cmd := exec.Command("/bin/bash","-c","cat ~/.bash_history")

这样是可以获取到了 history 命令了 多谢@channel 提醒。

channel
channel · #4 · 8年之前

赞啊 :thumbsup:

5kill
5kill · #5 · 8年之前

cmd := exec.Command("/bin/bash","-c","top -bn2")
top 命令 -b 批处理 n 循环显示次数

channel
channel · #6 · 8年之前
5kill5kill #5 回复

```cmd := exec.Command("/bin/bash","-c","top -bn2")``` top 命令 -b 批处理 n 循环显示次数

学习了

添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传