英文:
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.Command
的Stdout
属性。
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论