1

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
badman
  • 319
  • 1
  • 12

2 Answers2

5

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" )
atline
  • 28,355
  • 16
  • 77
  • 113
2

Here is another approach to change a file permission using os package

filepath.WalkDir(".", func(filePath string, f fs.DirEntry, e error) error {
    if e != nil {
        log.Fatal(e)
    }
    if filepath.Ext(f.Name()) == ".pem" {
        err := os.Chmod(filePath, 0400)
        if err != nil {
            log.Fatal(err)
        }
        fmt.Println(fmt.Sprintf("Successfully changed file permission, file: %s", filePath))
    }
    return nil
})

Complete code can be found at https://play.golang.org/p/x_3WsYg4t52

null
  • 548
  • 3
  • 14
  • Didn't work for me, tho it ran without errors, this could have been the best approach – badman Aug 12 '21 at 12:16
  • Did you see the log in the console "Successfully changed file permission, file:"? – null Aug 12 '21 at 14:01
  • Please replace "." with appropriate path if pem file location is different from execution dir. – null Aug 13 '21 at 07:32