supriya
supriya

Reputation: 965

Execute a command inside a particular directory using os/exec in golng

I want to run a command inside a particular directory.So here are 2 ways to do it.

command := exec.Command("echo *tar.gz | xargs -n1 tar zxf") 
command.Dir = pathFinal 
cmdErr := command.Run()

This is not working for me on the otherhand,

command := "cd "+pathFinal+"; "+"echo *tar.gz | xargs -n1 tar zxf" 
cmd := exec.Command("/bin/sh", "-c", command) 
cmdErr := command.Run()

This is working. I want to implement it the first way. I don't know why it is not working Second one throws an error

Failed to untar file: exec: "echo *tar.gz | xargs -n1 tar zxf": executable file not found in $PATH Am I missing something?

Upvotes: 0

Views: 1612

Answers (1)

Thundercat
Thundercat

Reputation: 120941

The first argument to Command specifies the executable to run. To run a shell pipe expression, execute a shell:

command := exec.Command("/bin/sh", "-c", "echo *tar.gz | xargs -n1 tar zxf") 
command.Dir = pathFinal 
cmdErr := command.Run()

Upvotes: 2

Related Questions