linux 脚本启动go程序,Go语言调用Shell与可执行文件

os/exec包可用于调用外部命令,可以使用管道连接输入输出,并支持阻塞与非阻塞方式执行命令。

os/exec包中关键的类型为Cmd,以下介绍的所有方法皆服务于该类型:

func Command(name string, arg ...string) *Cmd

方法返回一个*Cmd, 用于执行name指定的程序(携带arg参数)

func (c *Cmd) Run() error

执行Cmd中包含的命令,阻塞直到命令执行完成

func (c *Cmd) Start() error

执行Cmd中包含的命令,该方法立即返回,并不等待命令执行完成

func (c *Cmd) Wait() error

该方法会阻塞直到Cmd中的命令执行完成,但该命令必须是被Start方法开始执行的

func (c *Cmd) Output() ([]byte, error)

执行Cmd中包含的命令,并返回标准输出的切片

func (c *Cmd) CombinedOutput() ([]byte, error)

执行Cmd中包含的命令,并返回标准输出与标准错误合并后的切片

func (c *Cmd) StdinPipe() (io.WriteCloser, error)

返回一个管道,该管道会在Cmd中的命令被启动后连接到其标准输入

func (c *Cmd) StdoutPipe() (io.ReadCloser, error)

返回一个管道,该管道会在Cmd中的命令被启动后连接到其标准输出

func (c *Cmd) StderrPipe() (io.ReadCloser, error)

返回一个管道,该管道会在Cmd中的命令被启动后连接到其标准错误

普通调用示例:

调用Shell命令或可执行文件

演示在当前目录创建一个空文件

package main

import (

"fmt"

"os/exec"

)

func main(){

cmd := exec.Command("touch", "test_file")

err := cmd.Run()

if err != nil {

fmt.Println("Execute Command failed:" + err.Error())

return

}

fmt.Println("Execute Command finished.")

}

一般不建议使用这种默认方式调用Shell脚本:

cmd := exec.Command("my_shell.sh")

因为这种方式实际的执行结果和命令行执行#sh my_shell.sh一样,如果你的Shell脚本不满足sh的规范,就会调用失败。

调用Shell脚本

设置bash来调用指定Shell脚本,dir_size.sh为我们测试用的Shell脚本。调用完成后打印Shell脚本的标准输出到控制台。

package main

import (

"fmt"

"os/exec"

)

func main(){

command := `./dir_size.sh .`

cmd := exec.Command("/bin/bash", "-c", command)

output, err := cmd.Output()

if err != nil {

fmt.Printf("Execute Shell:%s failed with error:%s", command, err.Error())

return

}

fmt.Printf("Execute Shell:%s finished with output:\n%s", command, string(output))

}

dir_size.sh示例文件内容如下,用于输出当前目录的大小:

#!/bin/bash

du -h --max-depth=1 $1

Go程序运行结果:

[root@localhost opt]# ll

total 2120

-rwx------. 1 root root 36 Jan 22 16:37 dir_size.sh

-rwx------. 1 root root 2152467 Jan 22 16:39 execCommand

drwxrwxr-x. 11 1000 1000 4096 Jul 12 2017 kibana

drwx------. 2 root root 4096 Jan 16 10:45 sftpuser

drwx------. 3 root root 4096 Jan 22 16:41 upload

[root@localhost opt]# ./execCommand

Execute Shell:./dir_size.sh . finished with output:

4.0K ./sftpuser

181M ./kibana

1.1G ./upload

1.2G .

使用输入输出Pipe

演示使用管道连接到grep命令的标准输入,过滤包含test的字符串,并使用管道连接标准输出,打印运行结果:

package main

import (

"fmt"

"io/ioutil"

"os/exec"

)

func main(){

cmd := exec.Command("/bin/bash", "-c", "grep test")

stdin, _ := cmd.StdinPipe()

stdout, _ := cmd.StdoutPipe()

if err := cmd.Start(); err != nil{

fmt.Println("Execute failed when Start:" + err.Error())

return

}

stdin.Write([]byte("go text for grep\n"))

stdin.Write([]byte("go test text for grep\n"))

stdin.Close()

out_bytes, _ := ioutil.ReadAll(stdout)

stdout.Close()

if err := cmd.Wait(); err != nil {

fmt.Println("Execute failed when Wait:" + err.Error())

return

}

fmt.Println("Execute finished:" + string(out_bytes))

}

Go程序运行结果:

[root@localhost ~]# ./execCommand

Execute finished:go test text for grep

阻塞/非阻塞方式调用

文章开头方法介绍处已经介绍的很清楚,且前面示例都有涉及,就不另行说明了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在Linux中,可以使用shell脚本启动程序。以下是一个简单的示例: 1. 创建一个新的文本文件,例如"start_program.sh"。 2. 在文件中添加以下内容: #!/bin/bash cd /path/to/program ./program_name 其中,"/path/to/program"是程序所在的路径,"program_name"是要启动程序的名称。 3. 保存并关闭文件。 4. 在终端中,使用以下命令将文件设置为可执行: chmod +x start_program.sh 5. 最后,使用以下命令运行脚本: ./start_program.sh 这将启动程序并在终端中显示输出。如果您希望在后台运行程序,请使用以下命令: nohup ./start_program.sh > /dev/null 2>&1 & 这将在后台启动程序,并将输出重定向到/dev/null,以便不会在终端中显示。 ### 回答2: Linux是一个开源的操作系统,在使用过程中需要启动很多的程序。在Linux中可以使用shell脚本启动程序shell脚本是一种动态的脚本语言,它能够直接与系统内核交互,可以管理和操作操作系统的各种资源。下面详细介绍如何用shell脚本启动程序。 1. 创建一个shell脚本文件 在终端中使用touch命令创建一个文件并以.sh为扩展名,即为一个shell脚本文件。使用chmod命令将其设置为可执行状态。例如: touch myprogram.sh chmod +x myprogram.sh 2. 编写脚本文件 在文件中使用任何文本编辑器编辑脚本。一般情况下,创建一个包含启动命令和一些可选参数的脚本。例如: #!/bin/bash echo "Starting my program..." ./myprogram --arg1 --arg2 3. 运行脚本文件 运行shell脚本启动程序,需要在终端中输入以下命令: ./myprogram.sh 在这里“./”代表当前目录。如果脚本文件不在当前目录,则需要使用绝对路径或相对路径指定文件的位置。 4. 自动启动脚本文件 想让脚本程序自动启动,可以使用一些特殊的方式来完成。以systemd服务方式为例,可以创建一个.Unit文件,描述给定程序应该如何运行。包含要启动的路径,可选参数,依赖关系和其他设置。例如: [Unit] Description=My program After=network.target [Service] User=myuser ExecStart=/usr/local/bin/myprogram --arg1 --arg2 [Install] WantedBy=multi-user.target 然后使用systemctl命令将该服务启动。 systemctl start myprogram.service 在Linux系统中,可以使用shell脚本开启程序,使其在进程监视器中一直运行,同时保持脚本的独立性及可重用性。shell脚本是一个非常强大的工具,在Linux系统中具有广泛的应用。 ### 回答3: Linux Shell脚本可以运行程序,非常方便。下面我们将介绍如何使用Shell脚本启动程序。 1. 创建Shell脚本 首先,我们需要创建一个Shell脚本。用文本编辑器(例如vi)新建一个文件,以.sh结尾(例如myprogram.sh)。注意:文件名并不一定要与正在启动程序相同,但是它应该描述正在运行的程序。 2. 在Shell脚本中编写启动程序的命令 代码行的第一行应该是#!/bin/bash,以确保它以Bash shell执行。接下来,我们将编写运行程序的命令(例如./myprogram)。请记住,您需要为程序设置正确的路径。 3. 赋予脚本文件可执行权限 在终端中使用chmod命令,使Shell脚本文件可以执行: ``` $ chmod +x myprogram.sh ``` 4. 运行脚本文件 在终端中运行Shell脚本,可以使用./运算符,后跟文件名,例如: ``` $ ./myprogram.sh ``` 此时,您的程序已被启动。 通过Shell脚本启动程序非常方便,简单易行。只需创建Shell脚本,编写运行程序的命令,并赋予文件可执行权限,就可以启动你的程序了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值