英文:
It is possible to pass the value of user input into bash's command?
问题
以下是翻译好的代码部分:
fmt.Print("输入有效的nbd:")
reader := bufio.NewReader(os.Stdin)
input, err := reader.ReadString('\n')
if err != nil {
fmt.Println("读取输入时发生错误,请重试", err)
return
}
input = strings.TrimSuffix(input, "\n")
mount := fmt.Sprintf("qemu-nbd -c /dev/%s /tmp/var/lib/vz/images/201/vm-201-disk-0.qcow2", input)
cmd := exec.Command("/bin/bash", "-c", mount)
cmd.Run()
mountCmd := fmt.Sprintf("mount /dev/%s /mnt", input)
cmd = exec.Command("/bin/bash", "-c", mountCmd)
cmd.Run()
你可以使用fmt.Sprintf
函数将用户输入的值传递给mount
变量的值。在mount
变量中,使用%s
占位符来表示用户输入的值。
英文:
fmt.Print("Enter valid nbd: ")
reader := bufio.NewReader(os.Stdin)
input, err := reader.ReadString('\n')
if err != nil {
fmt.Println("An error occured while reading input. Please try again", err)
return
}
input = strings.TrimSuffix(input, "\n")
cmd = exec.Command("/bin/bash", "-c", "qemu-nbd -c /dev/", input, "/tmp/var/lib/vz/images/201/vm-201-disk-0.qcow2")
cmd.Run()
cmd = exec.Command("/bin/bash", "-c", "mount /dev/", input, "p1 /mnt")
cmd.Run()
I want to pass user input, for example nbd7, to both exec.Command as I mentioned.
input = strings.TrimSuffix(input, "\n")
mount := qemu-nbd -c /dev/input /tmp/CentOS-7.7.1908-x64.qcow2
cmd = exec.Command("/bin/bash", "-c", mount, "echo stdout; echo 1>&2 stderr")
I have modified abit of my code. Any proper way that I can pass my input value into mount variable's value? /dev/input definitely not working.
答案1
得分: 1
可以的。代码是正确的,你可以使用cmd.String
来打印执行的命令。在执行过程中很可能会出现错误。
我建议你使用cmd.Output()
和cmd.StderrPipe()
进行调试。
// Output运行命令并返回其标准输出。
// 任何返回的错误通常都是*ExitError类型。
// 如果c.Stderr为nil,则Output会填充ExitError.Stderr。
英文:
It is possible. Code is correct, you can use cmd.String
to print executed command. There is most likely error during execution.
I would recommend to use cmd.Output()
and cmd.StderrPipe()
for debugging.
// Output runs the command and returns its standard output.
// Any returned error will usually be of type *ExitError.
// If c.Stderr was nil, Output populates ExitError.Stderr.
答案2
得分: 0
谢谢大家,代码以这种方式正确运行。
input = strings.TrimSuffix(input, "\n")
mount := fmt.Sprintf(`qemu-nbd -c /dev/%s /tmp/ios.qcow2`, input)
cmd = exec.Command("bash", "-c", mount)
cmd.Run()
mount1 := fmt.Sprintf(`mount /dev/%sp1 /mnt`, input)
cmd = exec.Command("bash", "-c", mount1)
cmd.Run()
英文:
Thanks everyone, the code is working correctly in this way.
input = strings.TrimSuffix(input, "\n")
mount := fmt.Sprintf(`qemu-nbd -c /dev/%s /tmp/ios.qcow2`, input)
cmd = exec.Command("bash", "-c", mount)
cmd.Run()
mount1 := fmt.Sprintf(`mount /dev/%sp1 /mnt`, input)
cmd = exec.Command("bash", "-c", mount1)
cmd.Run()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论