In Go, the exec package is used to execute external commands. When attempting to run an 'mv' command using wildcards ('./source-dir/*'), an error of "exit status 1" occurs with the output stating "No such file or directory." However, running the same command in the terminal with the wildcard succeeds.
Unlike in the shell, where the shell interprets the wildcard and expands it into a list of matching files, the exec package treats the wildcard literally as a single argument. This means that the 'mv' command sees a wildcard ('*') instead of a list of filenames.
To use wildcards in Go, there are two approaches:
import "path/filepath" files, err := filepath.Glob("./source-dir/*") if err != nil { // Handle error } cmd := exec.Command("mv", files...)
cmd := exec.Command("/bin/sh", "-c", "mv ./source-dir/* ./dest-dir")
To recursively move all files from a source directory to a destination directory, you would need to recursively iterate through the source directory, and move each file or directory that is found. If the source contains subdirectories, you could either recursively move each subdirectory or use a package like os that provides functions for moving trees.
The above is the detailed content of Why Does My Go `exec.Command` Fail with Wildcards While the Terminal Succeeds?. For more information, please follow other related articles on the PHP Chinese website!