You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Go语言执行Shell内置命令?遇exit status 127错误求助

解决Go执行Shell内置命令history报错exit status 127的问题

问题原因

history是Shell的内置命令,并非独立可执行文件。默认通过sh -c启动的是非交互式Shell,这种模式下Shell不会启用历史记录功能,也不会读取历史记录文件,因此会返回"exit status 127"(表现为命令找不到)。

解决方案

要正常执行history,需要让Shell以交互式模式运行,或者手动启用历史记录并指定历史文件:

方案1:使用交互式Shell

通过-i参数让Shell以交互式模式启动,此时会自动加载配置并启用历史记录:

package main

import (
    "fmt"
    "os/exec"
)

func main(){
    // 用交互式sh执行history
    cmd := exec.Command("sh", "-ic", "history")
    stdout, err := cmd.Output()
    
    if err != nil {
        fmt.Println(err.Error())
        return
    }

    fmt.Println(string(stdout))
}

如果你的系统默认Shell是bash,也可以指定bash来执行:

cmd := exec.Command("bash", "-ic", "history")

方案2:手动启用历史记录(非交互式模式)

如果不想用交互式Shell,可以手动设置历史文件路径并启用history功能:

cmd := exec.Command("sh", "-c", "HISTFILE=~/.sh_history; set -o history; history")

注意:不同Shell的历史文件路径不同,bash对应~/.bash_history,sh/dash对应~/.sh_history,需要根据实际环境调整。

注意事项

  • 确保当前用户有历史记录文件的读取权限。
  • 不同系统的Shell行为可能略有差异,优先使用交互式模式的方案兼容性更好。

内容的提问来源于stack exchange,提问作者lool

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 16:12:08