英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论