Go Language Run shell command

Source: Internet
Author: User
This is a created article in which the information may have evolved or changed.
// go语言运行shell命令package mainimport (    "os/exec"    "fmt"    "os"    "strings")func main() {    var ip, whoami []byte    var err error    var cmd *exec.Cmd        // 执行单个shell命令时, 直接运行即可    cmd = exec.Command("whoami")    if whoami, err = cmd.Output(); err != nil {        fmt.Println(err)        os.Exit(1)    }    // 默认输出有一个换行    fmt.Println(string(whoami))    // 指定参数后过滤换行符    fmt.Println(strings.Trim(string(whoami), "\n"))        fmt.Println("====")        // mac平台获取ip地址    // 执行连续的shell命令时, 需要注意指定执行路径和参数, 否则运行出错    cmd = exec.Command("/bin/sh", "-c", `/sbin/ifconfig en0 | grep -E 'inet ' |  awk '{print $2}'`)    if ip, err = cmd.Output(); err != nil {        fmt.Println(err)        os.Exit(1)    }    fmt.Println(string(ip))    fmt.Println(strings.Trim(string(ip), "\n"))}

Effect:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.