Wednesday, October 27, 2021

[SOLVED] How to terminate a cat pipe command in shell script?

Issue

I use a command like to cat a pipe file and grep some data. A simple code such as,

temp=""
temp=$(cat file|grep "some data"| wc -c)
if [ $temp -gt 0 ]
then
    echo "I got data"
fi

The file is a pipe(FIFO), it will output data and not stop. How can i to terminate the command of cat pipe in a finite time?


Solution

grep|wc is the wrong tool for this job. Choose a better one, such as sed,

if sed -n -e '/some data/q;$q1' file; then
    ....
fi

awk,

found=$(awk '/some data/{print"y";exit}' file)
if [ -n "$found" ]; then
    ....
fi

or sh itself.

found=
while read line; do
    if expr "$line" : ".*some data" >/dev/null; then
        found=y
        break
    fi
done <file
if [ -n "$found" ]; then 
    ....
fi


Answered By - ephemient