dirkaka
dirkaka

Reputation: 118

Array in for loop in a BASH function

    function bookExistCheck {

    for i in "${bookTitle[@]}"
    do
        if [ "$1" == "${bookTitle[$i]}" ]; then
            if [ "${bookAuthor[$i]}" == "$2" ]; then
                bookExist=true
                echo "Book already exist in database."
            fi
        fi
    done

}

I am tryring to write a function that takes in 2 variables, title and author and then check if it already exist. BookTitle and BookAuthor are arrays which already hold values of book titles and authors. Currently with the above code, im getting an error on the line

 if [ "$1" == "{$bookTitle[$i]}" ]; then

The error says

./menu.sh: line 25: Harry Potter - The Half Blood Prince: syntax error in expression (error token is "Potter - The Half Blood Prince")

I am pretty new to BASH so my guess is a synthax error?

Upvotes: 0

Views: 50

Answers (1)

Vadim Beskrovnov
Vadim Beskrovnov

Reputation: 961

When you write for i in "${bookTitle[@]}", i isn't index of array, it's already element of array.

Try to write something like this: if [ "$1" == "${i}" ]; then

EDIT

You can also use for loop:

for (( i=0; i<=${#bookTitle[@]}; i++ )); do 

In this case, i will take indexes from 0 to bookTitle size.

Upvotes: 1

Related Questions