'grep command where value contains spaces

I have a file mail.txt with the following contents:

John Doe [email protected]
Mary Doe [email protected]

if I type the command in the console :

grep -ia 'John Doe' mail.txt 

I receive a result, but if I want to write it in a script, for example:

var="'John Doe'"
mail=mail.txt
result="`grep -ia $var $mail`"

I receive the error: grep: Doe': No such file or directory. How can this be solved?



Solution 1:[1]

You just need to use double quotes to assign the variable. So you can use double quotes again when defining the command. could look like this:

var="John Doe"
mail=mail.txt
grep -ia "$var" $mail

or

var="John Doe"
mail=mail.txt
result=`grep -ia "$var" $mail`
echo $result

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1