tags:

views:

70

answers:

3

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

+4  A: 

No, that's the standard way to do it. It shouldn't cause errors.

Matthew Flaschen
*It* shouldn't cause errors, but I might be more likely to. OTOH it's not that big a deal.
BCS
The only way it will fail is if the file ID for stdout is not 1 or the file ID for stderr is not 2. As these constants are defined by POSIX.1, which I believe is a prerequisite for bash to build, this will work for the forseeable future. Thus, I am curious as to what you mean by "likely to get edited wrong when things change". Are you having a similar problem with people changing the word "echo" into something else?
Mike DeSimone
Jefromi
`( echo something 1> something else ) > log` -> `(echo something; cp some junk 1> something else) > log` Oops.
BCS
IMHO, if someone messes with the code and doesn't know bash, this may be the least of your problems.
Mike DeSimone
I think if that's likely to be an issue, you should start using a different language: trying to make bash foolproof is a fool's venture.
intuited
+1  A: 

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.

n0rd
Better for it to be a function (like James Roth's answer), and better to pass along all arguments, not just the first.
Jefromi
+7  A: 

You could define a function:

function echoerr() { echo "$@" 1>&2; }
echoerr hello world

This would be faster than a script and have no dependencies.

James Roth