Enze Chi
Enze Chi

Reputation: 1763

Different result between run bash command directly and through exec.Command

On Linux OS, run "realpath ~/bin" gives the correct path "/home/user1/bin".

But when I run it as bellow:

cmd := exec.Command("realpath", "~/bin")
var out bytes.Buffer
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
    panic(err)
}
fmt.Println("Realapth:", out.String())

I got panic: exit status 1.

BTW: with command as below:

cmd := exec.Command("realpath", "--help")

I can get correct help message for realpath command. I think that means it is really in my executable path.

Upvotes: 2

Views: 247

Answers (1)

putu
putu

Reputation: 6444

If you run the command in a shell (e.g. bash), a tilde-prefix is expanded by the shell before being passed to realpath.

However if you run it in a go application, tilde is left as is and realpath assumes it as a part of the path name. To see the difference, you can try the following command in shell (Linux OS):

//1. correctly expanded
realpath './bin'

//2. tilde not expanded
realpath '~/bin'

//3. tilde expansion
realpath ~/bin

The (2) should failed, and the situation in your go application is similar to this. To verify, change your go code as follows:

cmd := exec.Command("realpath", "~/bin")
var out bytes.Buffer
var serr bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &serr
err := cmd.Run()
if err != nil {
    fmt.Printf("Error = %v, %v\n", err, serr.String())
    panic(err)
}
fmt.Println("Realapth:", out.String())

You should be able to observe error message produced by realpath command.

Upvotes: 1

Related Questions