Leon
Leon

Reputation: 1292

Bash compare strings not working

I am writing a bash script for a homework and it is required to build a mini library with some functions. I got almost all functions working except the search function. The if statement in line 11 is always true. I don't know how to compare that.

$lib="library"

function search_book {
echo Enter Book Title
read title
exists=`grep "$title" $library | wc -l`
if (( $exists == 0 ))
    then
    echo "No Such Book in Library"
else
    act_owner=`awk -F, '/'$title'/ {print $3}' $library`
    echo $act_owner
    if (( $act_owner == $lib ))
        then
        echo Book Kept In $act_owner
    else
        echo Book Checked Out by $act_owner
    fi
fi 
stop=0
while (( $stop == 0 ))
do
    echo
    echo "=========================="
    echo "(t) Try again"
    echo "(b) Back to main menu"
    echo -n 'Choose Option to Continue'
  read reply
  case $reply in 
  "t") stop=1; search_book;;
  "b") stop=1; main_menu;;
  *) echo illegal choice, enter again:
  esac
done
}

Upvotes: 1

Views: 128

Answers (1)

anubhava
anubhava

Reputation: 785058

This if condition seems to be problem:

if (( $act_owner == $lib ))

Since (( and )) are used for arithmetic operations only and it is always evaluating to true because both operators get converted to numbers and if condition becomes (( 0 == 0 )) and that always evaluates to true.

Even this if condition:

(( 'abc' == 0 )) && date

will evaluate to true and print the date for the same reason.

FIX: Change that condition to:

if [[ $act_owner == $lib ]]

Upvotes: 5

Related Questions