Home > Backend Development > Golang > Why Does My Go `exec.Command` Fail with Wildcards While the Terminal Succeeds?

Why Does My Go `exec.Command` Fail with Wildcards While the Terminal Succeeds?

Patricia Arquette
Release: 2024-12-08 09:27:12
Original
356 people have browsed it

Why Does My Go `exec.Command` Fail with Wildcards While the Terminal Succeeds?

Golang Exec Command Failure with Wildcards Despite Terminal Success

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.

Why Wildcards Fail in Go

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.

Solutions

To use wildcards in Go, there are two approaches:

  1. Use filepath.Glob(): This function returns a slice of strings containing the list of matching filenames for a given pattern. You can then use this list as arguments to the 'mv' command.
import "path/filepath"

files, err := filepath.Glob("./source-dir/*")
if err != nil {
    // Handle error
}

cmd := exec.Command("mv", files...)
Copy after login
  1. Invoke the Shell: You can invoke the shell and pass the command as an argument, allowing the shell to interpret the wildcard and expand it into the appropriate list of arguments.
cmd := exec.Command("/bin/sh", "-c", "mv ./source-dir/* ./dest-dir")
Copy after login

Recursive File Movement

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template