Golang failed to execute exec command that works in terminal

I get an error when I try to use the exec package to run the mv command.

Here is an example of what I'm trying to do:

 cmd := exec.Command("mv", "./source-dir/*", "./dest-dir") output, err := cmd.CombinedOutput() cmd.Run() 

err returns the following exit status 1

Result

returns mv: rename ./source-dir/* to ./dest-dir/*: No such file or directory

I can really get the script to work when I modify this line:

cmd := exec.Command("mv", "./source-dir/*", "./dest-dir")

to the next:

cmd := exec.Command("mv", "./source-dir/file.txt", "./dest-dir")

The command works and moves the file successfully, but using the template does not work. It does not appear that the asterisk is used as a wildcard in the command. Why is this? Is there any other way to use wildcards in GO? If not, how else could I recursively move all files from source-dir to dest-dir ?

thanks

+5
source share
1 answer

When you enter a command in the shell, the shell takes ./source_dir/* and replaces it with a list of all the files that match, one per argument. The mv command sees a list of file names, not a wildcard.

What you need to do is either do the same yourself (using filepath.Glob , which returns []string matching files), or call the shell so that it can do the job (using exec.Command("/bin/sh", "-c", "mv ./source_dir/* ./dest_dir") ).

+12
source

All Articles