Search code examples
arraysbashgrep

How to properly pass a $string with spaces into grep


i tried to make bash script that can find "keyword" inside *.desktop file. my approach is to set some keyword as array, then pass it to grep, it work flawlessly until the keyword has at least two word separated by space.

what it should be

cat /usr/share/applications/*.desktop | grep -i "Mail Reader"

what i have tried

search=$(printf 'Name=%s' "${appsx[$index]}")
echo \""$search\"" #debug
cat /usr/share/applications/*.desktop | grep -i $search
search=$(printf 'Name=%s' "${appsx[$index]}")
echo \""$search\"" #debug
cat /usr/share/applications/*.desktop | grep -i \""$search\""
search=$(printf '"Name=%s"' "${appsx[$index]}")
echo $search #debug
cat /usr/share/applications/*.desktop | grep -i $search

any suggestions is highly appreciated


Solution

  • If you simply assign Mail Reader to the variable search like below

    search=Mail Reader
    

    bash would complain that Reader command is not found as it takes anything after that first blank character to be a subsequent command. What you need is

    search="Mail Reader" # 'Mail Reader' would also do.
    

    In the case of your command substitution, things are not different, you need double quote wrappers though, as the substitution itself would not happen inside the single quotes

    search="$(command)"
    

    In your case, you did an overkill using a command substitution though. It could be well simplified to:

    search="Name=${appsx[$index]}"
    # Then do the grep.
    # Note that cat-grep combo could be simplified to
    # -h suppresses printing filenames to get same result as cat .. | grep
    grep -ih "$search" /usr/share/applications/*.desktop