Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 728
User10 Avatar asked Oct 19 '25 03:10

User10


1 Answers

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.

like image 152
William Pursell Avatar answered Oct 21 '25 16:10

William Pursell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!