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"
The correct thing to do is 2>errors. txt 1>&2 , which will make writes to both stderr and stdout go to errors. txt , because the first operation will be "open errors. txt and make stderr point to it", and the second operation will be "make stdout point to where stderr is pointing now".
The real question is: if someone were to redirect the output of your script to a file, would you want the warning placed in the file, or directed to the user? If you're expecting the user to take some action as a result of the warning, it should go to STDERR.
Warning messages are normally written to sys. stderr , but their disposition can be changed flexibly, from ignoring all warnings to turning them into exceptions.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With