Wednesday, April 23, 2014

The reason why we use stderr and stdout

The usage of stdout and stderr are rather important in programs.. However this is often done wrong.

The objective is:
  • stdout is the main program output.
  • stderr is for things that you want the user to see and pay attention to.
This is because in calls to sub processes, what you are aiming to do is get ONLY the good ouput captured and handled by the main script.. when there is an error you want this to bypass the normal path. Capturing the error contents is a problem because:
  • The user doesnt see it... unless
  • your main program has special code to detect and deal with error conditions from the sub program and then toss them upwards to the user. which is a total waste of your effort in most script systems where a simple return code will get you miles down the road much quicker
For example:
#first example toss an error from the remote
> A=`ssh ugly 'echo "error" 1>&2' ` 
error 
> echo $A 

#second example generate data from a remote and capture it
> A=`ssh ugly 'echo "data" 2>&1'` 
> echo $A 
data

#third example generate data from a remote and capture it. BUT also toss an error
> A=`ssh ugly 'echo "data" 2>&1; echo "error" 1>&2'` 
error 
> echo $A 
data

No comments:

Post a Comment