英文:
Different result between run bash command directly and through exec.Command
问题
在Linux操作系统上,运行"realpath ~/bin"会返回正确的路径"/home/user1/bin"。
但是当我按照下面的方式运行时:
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())
我得到了"panic: exit status 1"的错误。
顺便说一下,使用下面的命令:
cmd := exec.Command("realpath", "--help")
我可以得到"realpath"命令的正确帮助信息。我认为这意味着它确实在我的可执行路径中。
英文:
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.
答案1
得分: 1
如果您在shell(例如bash)中运行该命令,shell会在传递给realpath
之前扩展波浪线前缀。
然而,如果您在go应用程序中运行它,波浪线将保持不变,realpath
会将其视为路径名的一部分。为了看到区别,您可以在shell(Linux操作系统)中尝试以下命令:
//1. 正确扩展
realpath './bin'
//2. 波浪线未扩展
realpath '~/bin'
//3. 波浪线扩展
realpath ~/bin
第(2)个命令应该失败,您的go应用程序中的情况类似于此。为了验证,请将您的go代码更改如下:
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())
您应该能够观察到realpath
命令产生的错误消息。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论