Monday, October 14, 2013

Exit-status and Printf

www.unixbabuforum.inI have a question regarding timestamp and exit-status. 

COMMAND="echo test" 
${COMMAND} 2>&1 ; echo $? > exit_status | while read a 
do 
printf "$(date +%H:%M:%S) : " 
echo $a 
done 

I want to have a timestamp in front of each output - line, also I want to get the exit - status of the ${COMMAND}. In the way used above I don't get the timestamp, only the exit-status. In the way below I get the timestamp but no the exit-status. 

COMMAND="echo test" 
${COMMAND} 2>&1 | while read a 
do 
printf "$(date +%H:%M:%S) : " 
echo $a 
done 

www.unixbabuforum.in$ logcmd () { date "+%Y-%m-%d %T $($* >/dev/null 2>&1; echo $* $?)"; }
$ logcmd grep foo bar
2013-07-22 10:04:27 grep foo bar 2
$ cat explanation
1. "date" all by itself is perfectly capapble of echoing arguments
2. the command is/are the arguments, executed in the $( ... ) inside the date command
3. throw the output, and the stderr into /dev/null
4. echo the return code from the command
5. wrap it all in a function
$

www.unixbabuforum.inYou run command in a subshell, but you can't easily assign the status upwards. And in a complex pipeline, the status is probably not from command itself. 

You have to run command in a subshell and send the labelled result through the pipeline too, like: 

( echo "Start ZONK" ; command; echo "Ended ZONK status ${?}" ) | TimeStamper 

and read Marty's excellent blog to help write a generic TimeStamper function. 

Somewhere out the back of that will come 

16:47:04 Start ZONK 
your output ... 
23:48:18 Ended ZONK status 4 

Now it's easy to deal with from the log file. 

But also see my reservations about the inaccuracy of time stamps in pipelines.

0 comments:

Post a Comment

 
Design by BABU | Dedicated to grandfather | welcome to BABU-UNIX-FORUM