Search code examples
shellgoexecwildcard

Golang exec command chmod returning error


Familiarizing myself with Golang here and i am trying to execute shell commands, i need to chmod for any .pem file so i decided to use the wildcard *

func main() {

    cmd := exec.Command( "chmod", "400", "*.pem" )

    cmd.Stdout = os.Stdout
    cmd.Stderr = os.Stdout

    if err := cmd.Run(); err != nil {
        fmt.Println( "Error:", err )
    }

I keep get this error while executing:

chmod: cannot access '*.pem': No such file or directory
Error: exit status 1

Solution

  • Unlike the "system" library call from C and other languages, the os/exec package intentionally does not invoke the system shell and does not expand any glob patterns or handle other expansions, pipelines, or redirections typically done by shells.

    So here, * will not be expanded. As a workaround, you should use next to make it work:

    cmd := exec.Command("sh", "-c", "chmod 400 *.pem" )