Search code examples
shellstdoutstderrio-redirectionfish

How to print to stderr in fish shell?


In a fish-shell script, how do you print an error message to stderr?

For example, this message should go to the stderr stream rather than the default stdout stream.

echo "Error: $argv[1] is not a valid option"

Solution

  • You can redirect the output to stderr, for example:

    echo "Error: $argv[1] is not a valid option" 1>&2
    

    As a reference, here are some common IO-redirections that work in fish*.

    foo 1>&2 # Redirects stdout to stderr, same as bash
    
    bar 2>&1 # Redirects stderr to stdout, same as bash
    
    bar ^&1  # Redirects stderr to stdout, the fish way using a caret ^
    

    * The file descriptors for stdin, stdout, and stderr are 0, 1, and 2.
    * The & implies you want to redirect to a file stream instead of a file.
    * Comparison of redirection in various shells (bash, fish, ksh, tcsh, zsh)