How to check in golang if a particular directory has a mount –bind on it?

huangapple go评论104阅读模式
英文:

How to check in golang if a particular directory has a mount --bind on it?

问题

我使用以下命令来检查目录是否已挂载。

res := exec.Command("mount", "|", "grep", toDir, ">", "/dev/null").Run()

但是无论目录是否已挂载,它都返回 exit status 1

在命令行中运行正常。

我该如何获取这些信息?

英文:

I use following command to check if a directory is mounted.

res := exec.Command("mount", "|", "grep", toDir, ">", "/dev/null").Run()

But it returns exit status 1 no matter if a directory is mounted or not.

mount | grep /path/to/dir > /dev/null

On command line works fine.

How can I get the information?

答案1

得分: 1

你可以使用语言机制来进行管道操作,类似于以下代码:

c1 := exec.Command("mount")
c2 := exec.Command("grep", toDir)
c2.Stdin, _ = c1.StdoutPipe()
c2.Stdout = os.DevNull
c2.Start()
c1.Run()
c2.Wait()
英文:

You can use language machinery for piping, something like

c1 := exec.Command("mount")
c2 := exec.Command("grep", toDir)
c2.Stdin, _ = c1.StdoutPipe()
c2.Stdout = os.DevNull
c2.Start()
c1.Run()
c2.Wait()

答案2

得分: 1

由于您的命令涉及到管道操作,您可以将其作为命令字符串传递给bash,而不是直接执行它。类似这样的代码应该可以工作。

package main

import (
	"fmt"
	"os/exec"
)

func main() {
	res, _ := exec.Command("sh", "-c", "mount | grep /home").Output()
	fmt.Printf("%s", res)
}

请注意,这段代码使用Go语言编写,通过调用exec.Command函数来执行命令,并使用Output方法获取命令的输出结果。在这个例子中,命令是mount | grep /home,它会执行mount命令并将其输出通过管道传递给grep /home命令进行过滤。最后,通过fmt.Printf函数将结果打印出来。

英文:

Since your command involves pipes, you can pass it as a command string to bash instead of executing it directly. Something like this should work.

package main

import (
	"fmt"
	"os/exec"
)

func main() {
	res, _ := exec.Command("sh", "-c", "mount | grep /home").Output()
	fmt.Printf("%s", res)
}

huangapple
  • 本文由 发表于 2016年4月24日 17:52:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/36821613.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定