echo from a function
I have a function which works fine.
However, if I put it in a test statement then the echo does not work. I expected to see "calling my function" echoed to the screen, when I call it in these two places. if test myfun if [ myfun ] #here is my script function myfun { echo "calling my function" return 1 } myfun #this works if test myfun then echo one 1 else echo zero 0 fi if [ myfun ] then echo one 1 else echo zero 0 fi |
test works on the exit code; "$?", like this:
$ myfun $ echo $? If $? is 0, then the test worked, otherwise it is a failure. Suggestion: Say myfun gives 1 as output when it should test positively: MYFUN=$( myfun ) if [ "$MYFUN" -eq 1 ] then echo one 1 else echo zero 0 fi |
The behavior is correct in both cases, but maybe it is not what you want. The first if/then check the exit status of the command
Code:
test myfun Code:
if myfun |
No, I mean, when I call the function in the "if [ myfun ] " line, I would expect "calling my function" to go to the screen. Also if I redirect the output from the body of the function, it does not go to output.txt as I would expect.
function myfun { echo "calling my function" echo "this will go to output " > output.txt return 99 } if [ myfun ] then echo one else echo zero fi |
I try to be more clear: when you use the syntax
Code:
if [ expression ] Code:
if command |
All of the posts here are actually correct, but they may appear little confusing. So I will try to sort them out a little.
The functions in bash are handled different from C/C++. Let's say you define Code:
function myfun { Code:
myfun Code:
myfun But be careful. Code:
MYFUN=$(myfun) Code:
echo $MYFUN Now to that if commands. I think the difference between Code:
if [ expression ] Code:
if command Code:
if command So if you want a function to do something and than evaluate its return value, the construction should look like Code:
myfun |
Quote:
|
Coluxit you are right. I wrote it little bit confusingly. My error.
Code:
if command Code:
echo "true" Code:
echo "false" |
thanks
Thank you for all those replies. Very good stuff.
|
All times are GMT -5. The time now is 02:57 PM. |