bug:golang通过exec.Command()执行命令报错

bug:golang通过exec.Command()执行命令报错

1 通过exec指定zip命令报错

需求描述:压缩某个目录下的所有文件

  • 在执行过程中,发现zip命令可行,但是 /usr/bin/zip test.zip *发现无法压缩成功,程序直接报错退出,后来排查返现是golang中的exec.Command()不支持*通配符,但是我们可以通过下面的方式实现效果。

*替换为所有的文件名及目录:

package main

import (
	"fmt"
	"os/exec"
	"path/filepath"
)

func main() {
    
    
	zipName := "9999.zip"
	command := []string{
    
    
		"-r",
		zipName,
	}
	tmp, err := filepath.Glob("*")
	if len(tmp) == 0 {
    
    
		fmt.Println("No matching files found")
	}
	fmt.Println("* tmp=", tmp)
	command = append(command, tmp...)
	if err != nil {
    
    
		fmt.Println(err)
		return
	}
	fmt.Println("args=", command)

	cmd := exec.Command("/usr/bin/zip", command...)
	fmt.Println("compression cmd=", cmd)
	err = cmd.Run()
	if err != nil {
    
    
		fmt.Println("compression dir err=", err)
		return
	}

}

猜你喜欢

转载自blog.csdn.net/weixin_45565886/article/details/131320297
今日推荐