Home > Backend Development > Golang > Why Does `exec.Command()` Return Exit Status 1 When Running `sudo` Commands in Go?

Why Does `exec.Command()` Return Exit Status 1 When Running `sudo` Commands in Go?

Patricia Arquette
Release: 2024-11-27 13:45:10
Original
697 people have browsed it

Why Does `exec.Command()` Return Exit Status 1 When Running `sudo` Commands in Go?

Os Exec Sudo Command in Go

Background

While exploring Go and goroutines, users may encounter difficulties executing commands with the format:

sudo find /folder -type f | while read i; do sudo -S chmod 644 "$i"; done
Copy after login

Question

  • Why does the command return "exit status 1"?
  • How to obtain a more detailed error message?

Answer

  • Cause of Exit Status 1: The exec.Command() function executes the specified program directly. However, the given command involves multiple programs connected through a shell script. To execute shell scripts, use the following syntax:
cmd := exec.Command("/bin/sh", "-c", "sudo find ...")
Copy after login
  • Detailed Error Messages: Obtain more detailed error messages by running the command directly in the terminal. If it fails, check for any error messages in the terminal output.

Code Modifications

Here's the modified code:

package main

import (
    "fmt"
    "os/exec"
)

func main() {
    cmd := exec.Command("/bin/sh", "-c", "sudo find /folder -type f | while read i; do sudo -S chmod 644 \"\"; done")
    out, err := cmd.CombinedOutput()
    if err != nil {
        fmt.Printf("Error: %s\nOutput: %s", err, out)
    }
}
Copy after login

The above is the detailed content of Why Does `exec.Command()` Return Exit Status 1 When Running `sudo` Commands in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template