Is there a standard Bash tool that acts like echo but outputs to stderr rather than stdout?
I know I can do echo foo 1>&2
but it's kinda ugly and, I suspect, error prone (e.g. more likely to get edited wrong when things change).
Is there a standard Bash tool that acts like echo but outputs to stderr rather than stdout?
I know I can do echo foo 1>&2
but it's kinda ugly and, I suspect, error prone (e.g. more likely to get edited wrong when things change).
You could do this, which facilitates reading:
>&2 echo "error"
>&2
copies file descriptor #2 to file descriptor #1. Therefore, after this redirection is performed, both file descriptors will refer to the same file: the one file descriptor #2 was originally referring to. For more information see the Bash Hackers Illustrated Redirection Tutorial.
alias
in a shell script. It would probably be safer to use errcho(){ >&2 echo $@; }
Jul 13, 2015 at 21:52
2>&1
it means point 2 where 1 is _currently_ pointing to
so now if you wrongly write 2>&1 >file
, it reads point 2 where 1 is already going and point 1 to a file
so 2 now goes where 1 used to go but 1 no longer goes there... On the contrary >file 2>&1
reads point 1 to this file and point 2 to where 1 is currently pointing to
. &
can thus be read as where
.
You could define a function:
echoerr() { echo "$@" 1>&2; }
echoerr hello world
This would be faster than a script and have no dependencies.
Camilo Martin's bash specific suggestion uses a "here string" and will print anything you pass to it, including arguments (-n) that echo would normally swallow:
echoerr() { cat <<< "$@" 1>&2; }
Glenn Jackman's solution also avoids the argument swallowing problem:
echoerr() { printf "%s\n" "$*" >&2; }
echoerr -ne xt
is not going to print "-ne xt". Better use printf
for that.
Jun 24, 2014 at 13:23
echoerr() { cat <<< "$@" 1>&2; }
Jun 24, 2014 at 13:26
echoerr 'foo bar'
will have two spaces between foo
and bar
. (I had to add a zero-width joiner to make it show two spaces in this comment, so don't copy and paste it or it will be three spaces in the console).
Sep 29, 2016 at 12:49
$IFS
whitespace is sent as a separate argument, which in the case of echo
means concatenating them with 0x20
s, but the dangers of not quoting far outweight the convenience of 2 less characters to type).
Sep 29, 2016 at 19:56
Since 1
is the standard output, you do not have to explicitly name it in front of an output redirection like >
. Instead, you can simply type:
echo This message goes to stderr >&2
Since you seem to be worried that 1>&2
will be difficult for you to reliably type, the elimination of the redundant 1
might be a slight encouragement to you!
> &2
will not work, no whitespaces allowed there :)
May 7, 2021 at 20:05
Another option
echo foo >>/dev/stderr
foo
- has its own stderr redirected - e.g. foo >foo.log 2>&1
- then echo foo >/dev/stderr
will clobber all the output before it. >>
should be used instead: echo foo >>/dev/stderr
/proc/self/fd/2
. See my answer below :)
Sep 3, 2017 at 1:51
No, that's the standard way to do it. It shouldn't cause errors.
1>&2
. We all wish this wouldn't happen, but I'm sure we've all been places where it does.
( echo something 1>&2 ; something else ) > log
-> (echo something; cp some junk 1>&2 ; something else) > log
Oops.
If you don't mind logging the message also to syslog, the not_so_ugly way is:
logger -s $msg
The -s option means: "Output the message to standard error as well as to the system log."
Another option that I recently stumbled on is this:
{
echo "First error line"
echo "Second error line"
echo "Third error line"
} >&2
This uses only Bash built-ins while making multi-line error output less error prone (since you don't have to remember to add &>2
to every line).
cat
or any other utility, which is off-topic for the question.
Nov 27, 2019 at 19:09
Note: I'm answering the post- not the misleading/vague "echo that outputs to stderr" question (already answered by OP).
Use a function to show the intention and source the implementation you want. E.g.
#!/bin/bash
[ -x error_handling ] && . error_handling
filename="foobar.txt"
config_error $filename "invalid value!"
output_xml_error "No such account"
debug_output "Skipping cache"
log_error "Timeout downloading archive"
notify_admin "Out of disk space!"
fatal "failed to open logger!"
And error_handling
being:
ADMIN_EMAIL=root@localhost
config_error() { filename="$1"; shift; echo "Config error in $filename: $*" 2>&1; }
output_xml_error() { echo "<error>$*</error>" 2>&1; }
debug_output() { [ "$DEBUG"=="1" ] && echo "DEBUG: $*"; }
log_error() { logger -s "$*"; }
fatal() { which logger >/dev/null && logger -s "FATAL: $*" || echo "FATAL: $*"; exit 100; }
notify_admin() { echo "$*" | mail -s "Error from script" "$ADMIN_EMAIL"; }
Reasons that handle concerns in OP:
Other reasons:
My suggestion:
echo "my errz" >> /proc/self/fd/2
or
echo "my errz" >> /dev/stderr
echo "my errz" > /proc/self/fd/2
will effectively output to stderr
because /proc/self
is a link to the current process, and /proc/self/fd
holds the process opened file descriptors, and then, 0
, 1
, and 2
stand for stdin
, stdout
and stderr
respectively.
The /proc/self
link doesn't work on MacOS, however, /proc/self/fd/*
is available on Termux on Android, but not /dev/stderr
. How to detect the OS from a Bash script? can help if you need to make your script more portable by determining which variant to use.
/proc/self
link doesn't work on MacOS, so I'll stick with the more straight-forward /dev/stderr
method. Also, as noted in other answers/comments, it is probably better to use >>
to append.
/proc/self/fd/*
is available on Termux on Android, but not /dev/stderr
.
echo -n "has '/proc/self/fd/2': " ; [ -e /proc/self/fd/2 ] && echo true || echo false
or using that: echo -n "has '/dev/stderr': " ; [ -e /dev/stderr ] && echo true || echo false
Dec 5, 2020 at 12:02
Don't use cat
as some have mentioned here. cat
is a program
while echo
and printf
are bash (shell) builtins. Launching a program or another script (also mentioned above) means to create a new process with all its costs. Using builtins, writing functions is quite cheap, because there is no need to create (execute) a process (-environment).
The opener asks "is there any standard tool to output (pipe) to stderr", the short answer is : NO ... why? ... redirecting pipes is an elementary concept in systems like unix (Linux...) and bash (sh) builds up on these concepts.
I agree with the opener that redirecting with notations like this: &2>1
is not very pleasant for modern programmers, but that's bash. Bash was not intended to write huge and robust programs, it is intended to help the admins to get there work with less keypresses ;-)
And at least, you can place the redirection anywhere in the line:
$ echo This message >&2 goes to stderr
This message goes to stderr
cat
and instructing someone not to use cat because it's slow. There are countless use cases where cat is the right choice, so that's why I object to your answer.
Feb 18, 2019 at 21:56
echo
replacement. Even if he use cat
, he has to use a bash redirect. anyway. So, there is absolute no sense in to use cat
here. BTW I use cat
100 times a day, but never in the context the opener asked for... you got it?
This is a simple STDERR function, which redirect the pipe input to STDERR.
#!/bin/bash
# *************************************************************
# This function redirect the pipe input to STDERR.
#
# @param stream
# @return string
#
function STDERR () {
cat - 1>&2
}
# remove the directory /bubu
if rm /bubu 2>/dev/null; then
echo "Bubu is gone."
else
echo "Has anyone seen Bubu?" | STDERR
fi
# run the bubu.sh and redirect you output
tux@earth:~$ ./bubu.sh >/tmp/bubu.log 2>/tmp/bubu.err
Combining solution suggested by James Roth and Glenn Jackman
echoerr() { printf "\e[31;1m%s\e[0m\n" "$*" >&2; }
# if somehow \e is not working on your terminal, use \u001b instead
# echoerr() { printf "\u001b[31;1m%s\u001b[0m\n" "$*" >&2; }
echoerr "This error message should be RED"
read
is a shell builtin command that prints to stderr, and can be used like echo without performing redirection tricks:
read -t 0.1 -p "This will be sent to stderr"
The -t 0.1
is a timeout that disables read's main functionality, storing one line of stdin into a variable.
Make a script
#!/bin/sh
echo $* 1>&2
that would be your tool.
Or make a function if you don't want to have a script in separate file.
Here is a function for checking the exit status of the last command, showing error and terminate the script.
or_exit() {
local exit_status=$?
local message=$*
if [ "$exit_status" -gt 0 ]
then
echo "$(date '+%F %T') [$(basename "$0" .sh)] [ERROR] $message" >&2
exit "$exit_status"
fi
}
Usage:
gzip "$data_dir"
or_exit "Cannot gzip $data_dir"
rm -rf "$junk"
or_exit Cannot remove $junk folder
The function prints out the script name and the date in order to be useful when the script is called from crontab
and logs the errors.
59 23 * * * /my/backup.sh 2>> /my/error.log