Thursday, March 4, 2010

Command o/p redirection in bash (1)

How do you redirect command o/p in bash?

The simple answer is

bash$ command > out.txt

But, this is only a simple answer. There is much more that one might need to do. Consider a program like the one below.

#include <stdio.h>

int main()
        fprintf(stdout,"Stdout message\n");
        fprintf(stderr,"Stderr message\n");

    return 0;


If you compile and runt the above program this is what you will see.

[root@DER01C c]# ./a.out > out.txt
Stderr message
Stderr message
Stderr message

Why is that? It is because the above redirection does not take care of the stderror. It only redirects only stdout.

How to fix this problem? replace '>' with '&>'

[root@DER01C c]# ./a.out &> out.txt

But, then you will have to segregate the error and out put messages from out.txt. How to avoid this problem?

About that in my next post...

No comments: