Shell – Bash Script Function Return True-False

exit-statusfunctionshell-script

I want to query the function by returning the value.
My codes are as follows;

check(){
    file=/root/Turkiye.txt
    local funkx=$1
    while read line; do
        if [ "$line" == "$funkx" ]
        then
            true
            break
        else
            false
        fi
    done < $file
}

printf "Please enter the value : "
read keyboard

if check $keyboard;
then
    echo "yes";
else
    echo "no";
fi

It does not work, what am I doing wrong?

Best Answer

true and false are commands that exit with success and failure exit codes, respectively. They do not make your function return those values, to do that use the return command, and integer values corresponding to success (0) or failure (anything other than 0). Also, I'm pretty sure you don't want to return failure for the first line that doesn't match, just if no line matched:

check(){
    file=/root/Turkiye.txt
    local funkx=$1
    while read line; do
        if [ "$line" == "$funkx" ]
        then
            return 0    # 0 = success ("true"); break is not needed because return exits the function
        fi
    done < $file
    # If a line matched, it won't get here (it will have returned out of the middle
    # of the loop). Therefore, if it gets here, there must not have been a match.
    return 1    # 1 = failure ("false")
}

But there's a much simpler way to do this. Use grep -- its job is to search files for matching lines. You want grep -Fxq -- -F means search for fixed strings (not regular expression patterns), -x means require the whole line to match, not just part of it, and -q means don't bother printing the result, just exit with success status if a match was found, failure otherwise. And you don't even need an explicit return command, since the function will implicitly return the status of the last command in it:

check(){
    file=/root/Turkiye.txt
    local funkx=$1
    grep -Fxq "$funkx" "$file"
}

Or even simpler:

check(){
    grep -Fxq "$1" /root/Turkiye.txt
}
Related Question