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
Execute Shell Command Using the os/exec Package in Go It provides two functions that can be used to do this: Command, which creates the cmd object, and Output, which executes the command and returns the standard output. Output: Copy It will return the location of your current working directory.
The exec command is a powerful tool for manipulating file-descriptors (FD), creating output and error logging within scripts with a minimal change. In Linux, by default, file descriptor 0 is stdin (the standard input), 1 is stdout (the standard output), and 2 is stderr (the standard error).
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")
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With