我的bash脚本中的代码运行不稳定:
# check every line of check_list file presents in my_prog output
MY_LIST=`./my_prog`
for l in $(cat check_list); do
if ! echo -n "$MY_LIST" | grep -q -x "$l"; then
die "Bad line: '$l'"
fi
done
我的巨大脚本池中的这段代码显示“坏行:'smthng'”,概率大约为1/5000。我无法通过裸体脚本代表此事件,但只能在我庞大的脚本池中表示。
但是这段代码似乎工作得很好:
# check every line of check_list file presents in my_prog output
./my_prog > my_list
for l in $(cat check_list); do
if ! grep -q -x "$l" "my_list"; then
die "Bad line: '$l'"
fi
done
我不喜欢第二个语句的原因是它使用了一个中间文件“my_list”。 第一个陈述的不稳定工作可能是什么问题?
答案 0 :(得分:2)
您可以运行一个awk程序,而不是为check_list中的每一行调用grep:
awk '
FILENAME == ARGV[1] {check_list[$0]; next}
$0 in check_list {
print "bad line: " $0
exit 1
}
' check_list <(./my_prog)
或者,看看你的程序输出和check_list之间是否有任何共同的行:
common=$( comm -12 <(sort -u check_list) <(./my_prog | sort -u) )
if [ -n "$common" ]; then
echo "bad lines: "
echo "$common"
die
fi
答案 1 :(得分:1)
我不知道第一个版本有什么问题,但您可以轻松地消除临时文件的创建。 注意你必须纠正逻辑,我真的不明白,可能你会想要在内循环中更新变量并决定是否在内循环之后死掉。
for i in $*; do
for l in $(cat check_list); do
if ! echo "$i" | grep -q -x "$l"; then
die "Bad line: '$i', '$l'"
fi
done
done | ./my_prog