Home >Backend Development >Golang >Why Does My Go `exec.Command('mv', '*')` Fail with 'exit status 1'?

Why Does My Go `exec.Command('mv', '*')` Fail with 'exit status 1'?

DDD
DDDOriginal
2024-12-16 04:12:57535browse

Why Does My Go `exec.Command(

Go: Error "Failed to Execute Command" When Using Wildcard Character

When attempting to execute an "mv" command using Go's exec package, an error message stating "exit status 1" may occur. This issue arises when using wildcards, such as "*", in the command.

The problem lies in the way the shell interprets the command. When a wildcard is entered at the shell, it is expanded into a list of matching filenames. However, when using the exec package, the wildcard is not expanded, and the command is executed with the wildcard itself as an argument.

To resolve this issue, two approaches can be taken:

  1. Use filepath.Glob: Manually expand the wildcard into a list of filenames using the filepath.Glob function and pass the resulting slice as arguments to the exec package.
  2. Invoke the Shell: Utilize the shell's wildcard expansion capabilities by invoking it using exec.Command with "/bin/sh" as the binary and "-c" as the argument. The shell will then expand the wildcard before passing the command to the "mv" executable.

The above is the detailed content of Why Does My Go `exec.Command('mv', '*')` Fail with 'exit status 1'?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn