如何在shell脚本中终止cat管道命令?

时间:2012-09-25 16:59:40

标签: shell

我使用命令来捕获管道文件并grep一些数据。一个简单的代码,例如,

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

文件是管道(FIFO),它将输出数据而不是停止。如何在有限的时间内终止猫管的命令?

5 个答案:

答案 0 :(得分:0)

我在第3行添加了$ temp变量:

if [ $temp -gt 0 ]

因为你想要比较临时值,你可以在变量之前使用$。

关于文件“管道”,您可以执行cat,直到获得特定字符串。 我的意思是,您可以使用cat进行阅读,并在收到时停止,例如“\ n”。

我将举例说明您可以在终端中运行:

cat > example_file.txt << EOF
hello
I'm a example filen
EOF

cat将从标准输入读取,直到您输入“EOF”。然后,文件的内容将是:

cat example_file.txt 
hello
I'm an example file

因此,您可以通过块读取,例如,行。

答案 1 :(得分:0)

grep|wc是这项工作的错误工具。选择一个更好的,例如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

sh本身。

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

答案 2 :(得分:0)

只需检查grep本身的退出状态:

if grep -q "some data" file; then
    echo "I got data"
fi

如果找到匹配项,-q会阻止将任何内容写入标准输出。

答案 3 :(得分:0)

另一种方法是使用shell脚本。

cat <some file and conditions> &
< perform your task>

kill $(pidof cat)

只要您一次运行一个“cat”实例,就可以正常工作。

答案 4 :(得分:0)

您可以使用timeout中的coreutils命令。

man timeout

NAME
       timeout - run a command with a time limit

SYNOPSIS
       timeout [OPTION] DURATION COMMAND [ARG]...
...

要等待10秒:

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

相关问题