LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Software (http://www.linuxquestions.org/questions/linux-software-2/)
-   -   cat and grep in a bash script do not show results desired. (http://www.linuxquestions.org/questions/linux-software-2/cat-and-grep-in-a-bash-script-do-not-show-results-desired-767812/)

okos 11-08-2009 10:39 PM

cat and grep in a bash script do not show results desired.
 
Hello
I am writing a script and I ran into a snag.
I want to see if contents in a file exist. Ive been fiddling with this for hours but still no success.

In this example I made, I have a file "doc.txt"
In the file I have:
Quote:

John
Frank
Fred
I wrote this script but there seems to be a problem with the syntax.
Code:

#!/bin/bash
N=1
while test "$N" -le "10" ; do
echo "enter name"; read x
if [ "$(cat doc.txt | grep '$x')" = "" ] ; then
echo "$x does not exist in doc.txt"
else
echo "$x exists in doc.txt"
fi
done
exit

It does not matter what name I enter in I still get the same results.
Quote:

enter name
Joe
Joe does not exist in doc.txt
enter name
John
John does not exist in doc.txt
enter name
There is a problem with
Code:

if [ "$(cat doc.txt | grep '$x')" = "" ] ; then
Any suggestions on how to correct this?

wfh 11-08-2009 10:48 PM

There are many ways to do this other than the way you're doing it, however, try changing your script like so:

Code:

  if [ `grep $x doc.txt` ] ; then
    echo "$x exists in doc.txt"
  else
    echo "$x does not exist in doc.txt"
  fi

Note the back-quotes. You're executing what comes in between.

See here for Command Substitution in LDP abs guide.

ghostdog74 11-08-2009 10:57 PM

Code:

grep text file 1>/dev/null && echo "exists" || echo "no"

okos 11-08-2009 11:35 PM

wfh,

Quote:

if [ `grep $x doc.txt` ] ; then
is missing a condition and did not work.


Quote:

Originally Posted by ghostdog74 (Post 3749894)
Code:

grep text file 1>/dev/null && echo "exists" || echo "no"

Thanks a bunch it works.

Could you explain && and ||

Here is my actual script: (This is what did not work)
Quote:

########### Add cifs to fstab
if [ "$(cat /etc/fstab | grep '${NAME[$N]}/$LIST')" = "" ] ; then

echo "//${IP[$N]}/$LIST /home/server/${NAME[$N]}/$LIST cifs credentials=/etc/samba/.smbpass,_netdev,uid=1000,gid=1000 0 0" >> /etc/fstab
fi
Perhaps if I change it to:
Quote:

grep grep '${NAME[$N]}/$LIST' /etc/fstab 1>/dev/null && \
echo "//${IP[$N]}/$LIST /home/server/${NAME[$N]}/$LIST cifs credentials=/etc/samba/.smbpass,_netdev,uid=1000,gid=1000 0 0" >> /etc/fstab

bigrigdriver 11-08-2009 11:39 PM

Action && condition 1 || condition 2
translates as
Action AND condition OR condition 2


All times are GMT -5. The time now is 10:26 AM.