15
votes

I am getting an error when I try to use the exec package to run a mv command.

Here is an example of what I am trying to do:

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

cmd.Run()

err returns the following exit status 1

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

I can actually get the script to work when I change this line:

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

to the following:

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

The command works and moves the file successfully but using the wildcard doesn't work. It appears that the asterisk isn't being used as a wildcard in the command. Why is that? Is there another way to use wildcards in GO? If not then how else would I be able to recursively move all files from the source-dir to the dest-dir?

Thanks

1
It only got one downvote, who knows why. I brought it back to 0.hobbs
@hobbs thanks. When I first looked at it, it was at -2JoeMoe1984

1 Answers

31
votes

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

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