Is it possible to execute a bash command including sudo
with exec.Command? For example the code below executes fine for Execute(“ls /”), but hangs during Execute(“sudo mkdir /test”).
What I think I would like is that the dialog that asks for password is being opened when it includes sudo
.
I am testing this on Manjaro Linux…
func main() {
//fmt.Println(Execute("ls /"))
fmt.Println(Execute("sudo mkdir /test"))
}
func Execute(command string) string {
cmd := exec.Command("bash", "-c", command)
// Make sure that a new separate process is created
// that won't be killed when this process exits
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
output, err := cmd.Output()
if err!=nil {
fmt.Println(err.Error())
}
return string(output)
}
I am asking because I am writing a program, that starts applications and scripts, for me. I know that such applications already exists, but I wanted to write it myself. For example, when I type gimp
in my starter program, I want it to start Gimp for me. And when I type fstab
, I want it to run sudo xed /etc/fstab
or sudo nano /etc/fstab
. Running xed /etc/fstab
works fine of course, but then I can’t edit the file.