1837800 Members
8567 Online
110120 Solutions
New Discussion

expr grep question

 
intp
Frequent Advisor

expr grep question

hi,

i execute the following statement and then see its output

echo $(expr " 50 * 60 "|bc ) | grep 'syntax'

echo $?
return 1 because it failed to find the word syntax.


But i get the same output for this too,

echo $(expr " abc * 60 "|bc ) | grep 'syntax'

echo $?
returns 1. ( but abc*60 throws error msg saying "syntax error on line 1, teletype" )

whats wrong ?


3 REPLIES 3
Patrick Wallek
Honored Contributor

Re: expr grep question

The most likely thing I can think of is that the error message "syntax error on line 1" is going to the standard error (file descriptor 2) and not standar out (file descriptor 1).

The pipe works only with standard out I think.

Try this:

echo $(expr "abc*60"|bc) 2>&1 | grep 'syntax'

echo $?

And see if you now get the desired results.
A. Clay Stephenson
Acclaimed Contributor

Re: expr grep question

Patrick is correct; errors in UNIX go to stderr (file descriptor 2) and grep in looking at stdin (fdes 1). In any event, you are going about this all wrong. Why not get the status of the bc command directly:

#!/usr/bin/sh

A=50
B=60
C=$(echo "${A} * ${B}" | bc)
STAT=${?}
if [[ ${STAT} -eq 0 ]]
then
echo "C = ${C}"
else
echo "Bc failed; status = ${STAT}" >&2
fi
exit ${STAT}

You don't need both expr and bc; bc will work with both integers and floting-point values so it's probably a better choice.
If it ain't broke, I can fix that.
Sandman!
Honored Contributor

Re: expr grep question

Not sure what you are trying to get at, so I'm purely guessing:

# echo $(expr " abc * 60 "|bc ) | grep 'syntax'

the above throws a syntax error because "abc" is undefined and if it were then put a $ sign before it to access its value:

# abc=10
# echo $(expr " $abc * 60 "|bc ) | grep 'syntax'

And if you wanted to switch stdout and stderr around then do:

# abc=10
# echo $(expr " $abc * 60 "|bc ) 1>&2 2>&1| grep 'syntax'

hope it helps!