LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Problem in checking function return value (https://www.linuxquestions.org/questions/programming-9/problem-in-checking-function-return-value-673540/)

viveksnv 10-01-2008 09:42 AM

Problem in checking function return value
 
Hello All,

I am newbie for linux.

I have problem for checking if the function executes correctly or not.

#!/bin/bash

function test()
{
echo "Function executed"
return 0
}

if [ test $? == "0" ]
then
echo "Success";
#Ends

i want to check the function execution with in the if condition.

Thanks in Advance.

CRC123 10-01-2008 09:58 AM

Be careful using 'test' as a function as there is bash command called 'test' (the bash command is actually the same thing as square brackets '[ ]'.

You need to run the function first, then perform the if statement on its return code($?)

When comparing numbers with the 'test' command (aka '[ ]'), you use special tags:
[ 0 -eq 0 ] means 0 == 0
[ 0 -lt 0 ] means 0 < 0
[ 0 -gt 0 ] means 0 > 0
[ 0 -le 0 ] means 0 <= 0
etc

also, 'if' statements need to be completed with 'fi'

Hko 10-01-2008 10:04 AM

First of all: Using 'test' as a name for a function, variable, or script-file is not a good idea. This is because there is nearly always a program called 'test' installed in UN*X / Linux system as a part of the system.

So, in the scripts below I changed the name of your function to 'mytest'.

Two possible scripts for what you are trying to do. (but you mixed the two ways, which doesn't work) :
Code:

#!/bin/bash

function mytest()
{
    echo "Function executed"
    return 0
}

mytest  # First call the function
if [ $? == "0" ] # Then check the code returned
then
    echo "Success";
fi ## you forgot 'fi' here to end the 'if' statement.

exit 0 # Not needed, but "Good practice" in general

But since you wanted the "if"-statement only to executed if the function returns 0, the if statement can be simpler:
Code:

#!/bin/bash

function mytest()
{
    echo "Function executed"
    return 0
}

if mytest
then
    echo "Success";
fi

exit 0


viveksnv 10-02-2008 01:17 AM

Thanks to all
 
More thanks to all.

Now i realize, this is a silly question.

I will do more home works.


All times are GMT -5. The time now is 03:22 PM.