Bash:取消并行等待grep的FOR循环执行



将grep放入FOR循环中,对找到的行执行一些操作,在FOR循环中对要搜索的值进行循环,从而提供并行执行,但结果并不总是可预测的。我想强制执行一点也不平行。

代码示例:

for __loopVar in $(seq 1 32)
do 
echo "do some stuff no so much time consuming"
echo "calculate __someTextVar"
for each_line in  $(grep -HiRF "$__someTextvar" --include *.log $PATH_logFiles)
do
echo "some other stuff, with each line returned by grep"
done
done

问题是,(我假设(在等待grep返回值时,它从下面的循环("一些东西"(混合一些全局变量开始。

注意:在多路径上运行Ubuntu 20.04.1 LTS。

您的循环是嵌套的,我认为这会给您带来一些困惑,因为我看不到外部循环的用途。

如果你添加一些这些值的基本回声,我希望它变得更加清晰/明显:

for __loopVar in $(seq 1 3)
do
echo "__loopVar value is ${__loopVar}"
for each_line in  $(grep -HiRF "no" --include sometext.txt $PATH_logFiles)
do
echo "__loopVar value2 is ${__loopVar}"
echo "each_line value2 is ${each_line}"
done
done

输出:

__loopVar value is 1
__loopVar value2 is 1
each_line value2 is sometext.txt:another
__loopVar value2 is 1
each_line value2 is b
__loopVar value2 is 1
each_line value2 is sometext.txt:and
__loopVar value2 is 1
each_line value2 is another
__loopVar value2 is 1
each_line value2 is d
__loopVar value is 2
__loopVar value2 is 2
each_line value2 is sometext.txt:another
__loopVar value2 is 2
each_line value2 is b
__loopVar value2 is 2
each_line value2 is sometext.txt:and
__loopVar value2 is 2
each_line value2 is another
__loopVar value2 is 2
each_line value2 is d
__loopVar value is 3
__loopVar value2 is 3
each_line value2 is sometext.txt:another
__loopVar value2 is 3
each_line value2 is b
__loopVar value2 is 3
each_line value2 is sometext.txt:and
__loopVar value2 is 3
each_line value2 is another
__loopVar value2 is 3
each_line value2 is d

我认为你想做的事情更像这样:

IFS=$'n'
for __loopVar in $(seq 1 3)
do
echo ${__loopVar}
for each_line in  $(cat sometext.txt)
do
echo "some other stuff, with each line returned by grep ${each_line}"
done
done

因此,转义空格(让文件的cat获得整行(然后循环行_loopVar次。

$cat sometext.txt
Line a
another b
some other c
and another d
last value is e
$ bash 2.sh
1
some other stuff, with each line returned by grep Line a
some other stuff, with each line returned by grep another b
some other stuff, with each line returned by grep some other c
some other stuff, with each line returned by grep and another d
some other stuff, with each line returned by grep last value is e
2
some other stuff, with each line returned by grep Line a
some other stuff, with each line returned by grep another b
some other stuff, with each line returned by grep some other c
some other stuff, with each line returned by grep and another d
some other stuff, with each line returned by grep last value is e
3
some other stuff, with each line returned by grep Line a
some other stuff, with each line returned by grep another b
some other stuff, with each line returned by grep some other c
some other stuff, with each line returned by grep and another d
some other stuff, with each line returned by grep last value is e

由于您提供了一个不完整的脚本,因此此代码仍然需要更改以匹配您的预期行为。(例如,将cat命令更改为您的工作grep(。

最新更新