Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang failed exec command that works in terminal

Tags:

go

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

like image 606
JoeMoe1984 Avatar asked Jul 17 '15 01:07

JoeMoe1984


People also ask

How do I run a shell command in Golang?

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.

What is exec command?

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).


1 Answers

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")).

like image 168
hobbs Avatar answered Oct 22 '22 00:10

hobbs