0

Given the following programme which reads in user input twice

function search_grep
{
   if [ "$2" == "" ];then
    for x in "${title[@]}" 
    do
    value=$(echo $x | grep "$1")

        if [ "$value" != "" ];then
        echo "$value"
        fi      

    done
   elif [ "$1" == "" ];then
    hello="123"
    echo "$hello"   

   fi          

}

echo -n "Enter title : "
read book_title

echo -n "Enter author : "
read author

title=(CatchMe HappyDay)
search_grep $book_title $author

it works as expected when i enter followed by HappyDay HOWEVER

When i enter foo followed by , I would expect console output to be

123

instead I am getting

Can someone explain to me , the programme is not executing the second elif loop though second input is

2 Answers 2

1

In both of your cases cases, the following:

search_grep $book_title $author

expands to a call with a single argument. Hence, the "then" clause is activated. The reason is that an unquoted argument consisting of whitespace expands to nothing and disappears. That is the way of bash.

If you want to pass search_grep two arguments, then you need to quote the variables:

search_grep "$book_title" "$author"
Sign up to request clarification or add additional context in comments.

Comments

0

As shown here, you might try using = instead of ==

Or for an empty string comparison try -z

1 Comment

it works for the first case , why wouldnt it work for the second case??

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.