User10
User10

Reputation: 89

grep command in an if statement

#!/bin/bash
read -p "enter search term here: " searchT

if [[ $(cat test.txt | grep -wi '$searchT') ]]; then     
    echo "$(cat test.txt | grep '$searchT' && wc -l) number of matches found"
    echo $(cat test.txt | grep '$searchT')

else echo "no match found"    

fi

exit 0

How do I make the script run if the if statement is true. when i run the script the script will output the else statement. because there is no value to compare with the grep command.

Upvotes: 3

Views: 17361

Answers (3)

William Pursell
William Pursell

Reputation: 212238

It's not precisely clear what you are trying to match, but remember that if takes a command and evaluates its returns value. grep succeeds if it matches, and fails if it does not. So you probably just want to do:

if grep -q -wi "$searchT" test.txt; then
   ...
fi 

Note that you should use double quotes so that "$searchT" is expanded and its value is passed as the argument to grep, and there is no need for cat.

In your original code, you have the line echo $(cat test.txt | grep '$searchT'), which has several issues, but I will just address the anti-pattern echo $(cmd). The $() gathers the output of cmd and passes it as arguments to echo, which then writes them. Instead of echo $(cmd), you can almost always just do cmd and cut out the middle man. (echo will squeeze whitespace and perhaps treat some of the output of cmd as flags, so the output is not always identical, but it is almost always what you want. If you are actually using echo $(cmd) intentionally to squash whitespace or are using flags in the output of cmd, you have a code readability issue!) In this case, there is an easier solution than using echo here, though. Just omit the -q from the grep command and let the output be written.

Upvotes: 11

glenn jackman
glenn jackman

Reputation: 246774

Here's another way to cache the results: mapfile consumes its stdin into an array, each line is an array element.

mapfile -t results < <(grep -wi "$searchT" test.txt)
num=${#results[@]}

if ((num == 0)); then
    echo "no match found"
else
    echo "found $num matches"
    printf "%s\n" "${results[@]}"
fi

Upvotes: 5

vgersh99
vgersh99

Reputation: 965

#!/bin/bash

if [ $((n=$(grep -wic "$searchT" test.txt))) -ge 0 ]; then
    echo "found ${n}"
else
    echo "not found ${n}"
fi

modified based on comments:

#!/bin/bash

if n=$(grep -wic "$searchT" test.txt); then
    echo "found ${n}"
else
    echo "not found ${n}"
fi

Upvotes: 2

Related Questions