centos – if condition always false despite the condition being true upon manual execution

I wish to search for a string mongo and not starting with comment i.e # in a file.

homedir=`ls -d ~`

echo "$homedir"

if [[ `cat $homedir/2_need_softwares.txt | grep -v '^#' | grep -iq mongo` ]]; then

echo "Installing mongodb"

else

echo "skipping mongo"

fi

Output:

/root
skipping mongo

I’m on centos 9

$ uname -a
Linux DKERP 5.14.0-134.el9.x86_64 #1 SMP PREEMPT_DYNAMIC Thu Jul 21 12:57:06 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux

As you see the if statement is failing and hence the else gets executed.

But when I run the if condition manually it shows success

$ cat /root/2_need_softwares.txt | grep -v '^#' | grep -iq mongo
$ echo $?
0

$ grep mongo /root/2_need_softwares.txt
mongo

Can you please suggest what is wrong with my if condition?

I tried the below as well:

1. if [[ $(cat $homedir/2_need_softwares.txt | grep -v '^#' | grep -iq mongo) ]]; then

2. if [[ $("cat $homedir/2_need_softwares.txt | grep -v '^#' | grep -iq mongo") ]]; then

This is for bash and POSIX is preferred.

Read more here: Source link