简体   繁体   中英

Command executes but code doesn't return error for non existing commands

Code in function to run a fzf against an input, while debugging i discovered my code doesn't return errors, this code runs successfully:

    reader := strings.NewReader(listOutput.String())

    r, w, _ := os.Pipe()
    os.Stdout = w

    cmd := exec.Command("fzf", "--multi")
    cmd.Stdin = reader
    cmd.Stderr = os.Stderr
    if err := cmd.Run(); err != nil {
        fmt.Println("Couldn't call fzf: %v", err)
    }

    w.Close()

So i changed the command to something that doesn't exist, but the code still doesn't return "couldn't call command: command not found", just exits.

    reader := strings.NewReader(listOutput.String())

    r, w, _ := os.Pipe()
    os.Stdout = w

    cmd := exec.Command("idontexist")
    cmd.Stdin = reader
    cmd.Stderr = os.Stderr
    if err := cmd.Run(); err != nil {
        fmt.Println("Couldn't call command: %v", err)
    }

    w.Close()

I don't have an idea what could be wrong.

cmd.Run() does return an error, and your if block gets properly executed, but since you change the standard output os.Stdout = w you just don't see the result on your console / terminal.

The fmt package writes to the standard output.

If you use the log package, you will see the error as the log package writes to the standard error (which you didn't change):

log.Printf("Couldn't call command: %v", err)

This will output something like (note the default log format includes the timestamp too):

2022/12/07 13:46:19 Couldn't call command: exec: "idontexist": executable file not found in $PATH

Or don't change the standard output.

Also do note that log.Println() and fmt.Println() do not require a format string. Do use log.Printf() and fmt.Printf() when you specify a format string and arguments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM