简体   繁体   English

如何 grep 在 for 循环中成功

[英]How to grep success in a for loop

Struggling with this...正在为此苦苦挣扎……

for i in `cat services.txt`
do
if ! grep -q $i; then
echo " $i Is NOT Running"
else
echo " Checking $i on `hostname`..."
ps aux | grep -i $i | awk '{print $1, $11}'| cut -d' ' -f1-2| sort
echo -e " "
sleep 4
fi
done

The block just hangs - Ive not been able to capture the success/failure of grep该块只是挂起 - 我无法捕捉 grep 的成功/失败

If a string in services.txt is NOT found... the script hangs... Id like for grep to skip it if not found如果未找到 services.txt 中的字符串...脚本挂起...如果未找到 grep 则跳过它

services.txt contain just single words services.txt 仅包含单个单词

thanks!谢谢!

The reason your script hangs is beacuse the command grep -q $i is waiting for an input.您的脚本挂起的原因是因为命令grep -q $i正在等待输入。 You can try running that command separately in a shell and verify that it prompts for an input.您可以尝试在 shell 中单独运行该命令,并验证它是否提示输入。

Changing your command to ps aux | grep -i $i将命令更改为ps aux | grep -i $i ps aux | grep -i $i in the if statement should fix your issue. if 语句中的ps aux | grep -i $i应该可以解决您的问题。

NOTE: ps aux | grep -i $i注意: ps aux | grep -i $i ps aux | grep -i $i lists grep also as one of the process. ps aux | grep -i $i列出 grep 也作为进程之一。 Make sure you exclude that process by piping it to another grep ps aux | grep -i $i | grep -v 'grep'确保通过管道将其排除在另一个 grep ps aux | grep -i $i | grep -v 'grep' ps aux | grep -i $i | grep -v 'grep'

here is the working code这是工作代码

checkservices() {
cat >$HOME/services.txt <<EOF
ganglia
hbase
hdfs
hive
hue
livy
mapred
test-missing-service
mysql
oozie
presto
spark
yarn
zeppelin
EOF

for i in `cat $HOME/services.txt`
do 
if `ps -ef  | grep ^$i | grep -v grep >/dev/null`
then 
i=$(echo "$i" | awk '{print toupper($0)}')
echo "$i -- is running on `hostname`"
echo ""
sleep 2
else 
i=$(echo "$i" | awk '{print tolower($0)}')
echo "$i -- IS NOT running on `hostname` error"
echo ""
fi
done
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM