Search code examples
bashunixscripting

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.


Solution

  • 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