Chanchal Roshan
Chanchal Roshan

Reputation: 174

condition evaluating to "TRUE"

I am trying to check for duplicate records in my database using shell scripting. For this, I have created a function named "check()" which echo's True or False and is stored in variable "result". But while evaluating using if statement it is always returning "True".

#redundancy check function
check() {
    temp=$(grep -w -c "$1" database.dat)
    echo $temp
    if [ "$temp" != 0 ]
        then
            echo True
        else
            echo False
    fi
}

insert() {
    option="y"
    while [ "$option" == "y" ]
    do
        echo "Rollno: \c"
        read roll
        result="$(check $roll)"
        echo $result
        if [ "$result" == "False" ]
            then        
                echo Do something
            else
                echo "ERROR: Duplicate record found...\nEXITING...\n"
                option="n"
        fi
    done
}

Upvotes: 0

Views: 42

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295278

If you're using a shell that doesn't support the == extension to test, then your tests will always, unconditionally fail simply on account of invalid syntax. Use = for string comparisons to be portable to all POSIX-compliant implementations.

Moreover, there's no point to storing and then comparing the output from grep at all: Use the exit status of grep -q when your only goal is to check whether the number of matches is zero or more-than-zero; this allows grep to exit immediately when a match is seen, rather than needing to read the rest of the file.

# with -q, this emits no stdout, but exits w/ status 0 (matches exist) or 1 (otherwise)
check() { grep -q -w -e "$1" database.dat; }

insert() {
  option=y
  while [ "$option" = y ]; do
    printf '%b\n' "Rollno: \c"
    read -r roll
    if check "$roll"; then
      printf "ERROR: Duplicate record found...\nEXITING...\n"
      option=n
    else
      echo "Check failed; do something"
    fi
  done
}

Upvotes: 1

Related Questions