Executing mv Commands Differently in Go and Bash
In Go, using the exec package to execute the mv command can lead to issues when using wildcards like "*" in the command arguments. While the command works as expected in the terminal, the asterisk wildcard doesn't seem to work in the Go script.
The reason for this discrepancy lies in how the shell and Go handle command arguments. In the terminal, the shell interprets the wildcard and replaces it with a list of matching filenames. However, in Go, the command is passed as a string, and it sees the wildcard literally as part of the argument.
To work around this issue, you have two options:
Expand Wildcards Manually
You can use Go's filepath.Glob function to fetch a list of files that match the wildcard pattern, and then pass the individual filenames as arguments to exec.Command. For example:
files, err := filepath.Glob("./source-dir/*") if err != nil { // Error handling } cmd := exec.Command("mv", files, "./dest-dir")
Use Shell Invocation
You can invoke the shell itself to execute the mv command with the wildcards. The shell will interpret the wildcards and pass the expanded arguments to the mv command. For example:
cmd := exec.Command("/bin/sh", "-c", "mv ./source-dir/* ./dest-dir")
By using one of these approaches, you can ensure that wildcards are handled correctly in your Go scripts, allowing you to execute mv commands as intended.
The above is the detailed content of Why Does `mv` with Wildcards Behave Differently in Go and Bash?. For more information, please follow other related articles on the PHP Chinese website!