views:

88

answers:

5

I want to know if there is a built-in BASH command that prints some text on stderr, just like the echo command that prints text on stdout. I don't want to use temporary io-redirection. I use a built-in command to generate an error on stderr such as ls --asdf (ls: unrecognized option '--asdf') but I want something neater.

Edit ----

Actually I am trying to demonstrate stderr/stdout redirection, and my example looks like:

sh test.sh >test-out.txt 2>test-err.txt

For clarity, I want to keep the test.sh file as simple and clean as possible, this means avoiding > operator inside the file.

A: 

No builtin, you could use:

function echo-err { echo "$@" >&2; }
Jürgen Hötzel
A: 

In general, I think that there is not really a difference between 'temporary io-redirection' and the thing you want. stderr is a file descriptor like any other, and any builtin that does what you want would just be doing the same thing internally that you do by redirecting echo as Jurgen suggested above, namely, calling write() on it.

Personman
A: 

You could also make an alias.

alias echoerr='echo >&2'
Chris Cooper
+2  A: 

echo something >&2 is the correct way to do what you want.

However...

This will create a little program that will echo its arguments to stderr:

gcc -o echoerr -x c - <<'EOF'
#include <stdio.h>
#include <stdlib.h>
void main(int argc, char **argv) {
    int i;
    for (i = 1; i < argc; i++) {
        fprintf(stderr, "%s ", argv[i]);
    }
    fprintf(stderr, "\n");
    exit(0);
}
EOF

You can use it like this:

$ ./echoerr this is an error message
this is an error message
$ ./echoerr this is an error message 2>error.out
$ cat error.out
this is an error message
Dennis Williamson
A: 

Just a sidenote: If you like to demonstrate bash, you should use bash, not sh:

sh test.sh >test-out.txt 2>test-err.txt
bash test.sh >test-out.txt 2>test-err.txt

Even if sh is a link to bash on your system, it will check how it was called (arg0) and treat sh-calls like an invocation

bash --posix 

which leads to sometimes subtile different behaviour. A common mistake, like shebangs #/bin/sh 'but it did work in the shell' (which was /bin/bash).

user unknown