运行程序时,使用exec.Command将标准输出重定向到/dev/null。

huangapple go评论76阅读模式
英文:

Run program w/ exec.Command redirecting stdout to /dev/null

问题

我正在将我的脚本从bash转换为go,不幸的是,我无法使pass命令正常工作。当我运行bash脚本时,我会收到一个窗口来提供我的密码给pass管理器。

这是我的go代码的一部分:

package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
)

func run_command(command *exec.Cmd) string {
	attach_json, err := command.Output()
	if err != nil {
		fmt.Println(err.Error())
		// os.Exit(0)
	}
	fmt.Println(attach_json)
	return string(attach_json)
}

email := "xyz@abc.com"
cmd_emamil := "GoJira/api-token:" + email
pass_cmd := exec.Command("pass", cmd_emamil, "> /dev/null")
pass_cmd := exec.Command("pass", cmd_emamil)
run_command(pass_cmd)

希望这可以帮助到你。

英文:

I am translating my script from bash to go and unfortunately I am not able to make pass command work. When I run the bash one I receive a window to provide my password to the pass manager.

Here is part of my go code:

package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
)

func run_command(command *exec.Cmd) string {
	attach_json, err := command.Output()
	if err != nil {
		fmt.Println(err.Error())
		// os.Exit(0)
	}
	fmt.Println(attach_json)
	return string(attach_json)
}

email := "xyz@abc.com"
cmd_emamil := "GoJira/api-token:" + email
pass_cmd := exec.Command("pass", cmd_emamil, "> /dev/null")
pass_cmd := exec.Command("pass", cmd_emamil)
run_command(pass_cmd)

答案1

得分: 3

在shell命令pass >/dev/null中,>/dev/null不是pass的参数,而是对shell的指令,告诉它在启动pass之前将文件描述符1(标准输出)替换为/dev/null的句柄。

当你使用exec.Command()时,实际上没有使用shell,所以你不能使用shell语法。相反,你可以将你想要重定向标准输出的文件分配给exec.CommandStdout属性。

devnull, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0755)
if err != nil { panic(err) }

cmd_email := "GoJira/api-token:" + email
pass_cmd := exec.Command("pass", cmd_email)
pass_cmd.Stdout = devnull
英文:

In the shell command pass >/dev/null, >/dev/null is not an argument to pass; instead, it's an instruction to the shell, telling it to replace file descriptor 1 (stdout) with a handle on /dev/null before pass is started.

When you use exec.Command() there is no shell, so you can't use shell syntax. Instead, assign the file you want stdout to be redirected to to the Stdout of your exec.Command.

devnull, err := os.OpenFile(os.DevNull, os.O_WRONLY, 0755)
if err != nil { panic(err) }

cmd_email := "GoJira/api-token:" + email
pass_cmd := exec.Command("pass", cmd_email)
pass_cmd.Stdout = devnull

huangapple
  • 本文由 发表于 2021年8月17日 05:52:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/68809595.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定