可以将用户输入的值传递给 bash 的命令吗?

It is possible to pass the value of user input into bash's command?

    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()

我想像我提到的那样将用户输入(例如 nbd7)传递给 exec.Command。

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")

我修改了一些代码。我可以将我的输入值传递给安装变量的值的任何正确方法吗? /dev/input 绝对不行。

有可能。代码是正确的,你可以使用 cmd.String 来打印执行的命令。执行过程中很可能出错。

我建议使用 cmd.Output()cmd.StderrPipe() 进行调试。

// 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.

谢谢大家,这样代码运行正常。

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()