LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Strange behavior (https://www.linuxquestions.org/questions/linux-newbie-8/strange-behavior-4175510684/)

battles 07-10-2014 07:44 AM

Strange behavior
 
I have these lines in a file called rogue.txt:
atd
bash
-bash
bdi-default
boa
cleanup

I search through the file one line at a time looking to see if one of the words is therein:
Code:

#!/bin/bash
#
while read line
do
if [ $(grep -c $line rogue.txt) -gt 0 ]
  then
  echo "word in rogue.txt"
  else
  echo "word not in rogue.txt"
fi
done <test.txt

When $line is -bash, the routine passes the echo "word not in rogue.txt" message and also causes the while loop to stop at that point. Any clues as to why this is happening?
Thanks.

rtmistler 07-10-2014 08:29 AM

This works fine. Firstly please place code within [code][/code] tags.

My contents of rogue.txt are the same as yours.

My contents of test.txt is the word bash.

The script as I've copied it, but note that I've indented as well as put in #!/bin/sh, I called it sear.sh:

Code:

#!/bin/sh

while read line
do
    if [ $(grep -c $line rogue.txt) -gt 0 ]
    then
        echo "word in rogue.txt"
    else
        echo "word not in rogue.txt"
    fi
done <test.txt

The output:

Code:

~/testcode$ ./sear.sh
word in rogue.txt
~/testcode$

If you're not seeing this, then I wonder if there are other parts of your script which you're not showing; can you elaborate and also check what shell you're running?

Another suggestion is to put the following near the top of your script to enable debugging output:

Code:

set -xv
HOWEVER, this all assumes you're using BASH.

battles 07-10-2014 08:40 AM

I put in the entire code above. Never seen set -xv, pretty nice debugging process.

rtmistler 07-10-2014 08:50 AM

Quote:

Originally Posted by battles (Post 5201704)
I put in the entire code above. Never seen set -xv, pretty nice debugging process.

Some other suggestions Blog Entry on BASH Programming.

battles 07-10-2014 08:55 AM

I resemble that remark: "Bash Scripting for Dummies" :)

Thanks (I think?).

rtmistler 07-10-2014 08:59 AM

"AND Geniuses" ... :)

Just toss yourself in the "other" pool.

Glad you got it working, and yes "set -xv" is extremely useful.


All times are GMT -5. The time now is 06:59 AM.