yonubear
Posts: 90
Joined: Thu Sep 12, 2013 11:11 pm

help with bash script and grep

Wed Mar 06, 2019 3:44 am

I am hoping that someone can help me out I am trying to get a bash script working with mosquito_sub to forward messages to another program but i am having no luck I am hoping someone here can point out what i am doing wrong basicly right now i am trying to find the word POWER in the messages

Code: Select all

#!/bin/bash

clean="output input cmds";p="backpipe";pid=$(cat pidfile)
ctrl_c() {
  echo "Cleaning up..."
  rm -f $p;rm "$clean";kill $pid 2>/dev/null
  if [[ "$?" -eq "0" ]];
  then
     echo "Exit success";exit 0
  else
     exit 1
  fi
}
([ ! -p "$p" ]) && mkfifo $p
(mosquitto_sub -h 192.168.1.8 -R -v -t "#" >$p 2>/dev/null) &
#echo "$!" > pidfile
while read line <$p
do
  echo $line
printf "%s: %s\n" "Power" "$(grep -o "Power" $line | wc -w)"
done


tpyo kingg
Posts: 640
Joined: Mon Apr 09, 2018 5:26 pm
Location: N. Finland

Re: help with bash script and grep

Wed Mar 06, 2019 5:23 am

If I am reading that correctly, the quotes need to be escaped, and then $line provided as input:

Code: Select all

printf "%s: %s\n" "Power" "$(echo $line | grep -o \"Power\" | wc -w)"
grep only reads stdin or files. The way you had it above it was looking for the file(s) identified in the content of the variable $line, which of course probably didn't even exist.

Also, grep is case sensitive. So if you are really looking for POWER, pOwEr, pOWER, etc and not just Power, add -i in there too.

Return to “General programming discussion”