0
    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?

6
  • try "${bookTitle[$i]}" Commented Jul 18, 2017 at 8:10
  • @delta Isnt that what my code currently is ? If you meant change [@] to [$i], that also doesnt work. Commented Jul 18, 2017 at 8:14
  • sorry. you have a single line if [ "$1" == "{$bookTitle[$i]}" ]; then. But the full function code is right. Commented Jul 18, 2017 at 8:15
  • can you give the input of bookExistCheck, and also bookTitle and bookAuthor? Commented Jul 18, 2017 at 8:18
  • @delta im sorry but i still dont understand what you are suggesting. That line is suppose to compare what i have stored in $bookTitle[i] to the first argument passed which is stored in $1 Commented Jul 18, 2017 at 8:19

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

OMG... I confused this for loop to the other for loop for($i=0;$i++....) Thank you for this. Your suggestion would work but i also have another bookAuthor argument i need to compare. Should i just put another for loop inside the bookTitle loop?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.