我创建了一个脚本,用于比较来自两个文件的值,并在两种情况下输出一个消息(成功或失败)。但后来我意识到,即使成功,脚本也会继续将主变量(jbid)与第二个文件中的所有其他变量(bsid)进行比较,这是我不想要的。当“if”遇到成功时,我希望第二个for循环结束。
我将tmpcsv2中的'jbsid'与文件bkid中的'bsid'进行比较。
for jbid in `cat tmpcsv`; do #1st Loop
for bsid in `cat bkid`; do #2nd Loop
ckid=`echo $bsid | cut -d "," -f1`
jbsiz=`echo $bsid | cut -d "," -f2`
if [ "$jbid" -eq "$ckid" ]; then
printf "There's a match at $ckid\n"
else
printf "No Match Found at $ckid\n"
fi
done
printf "Check for ID $jbid done\n"
sleep 2
done
我可能正在使用错误的方式执行此操作并打开更短/更清晰的形式!
答案 0 :(得分:1)
只需在真正的条件分支中添加“break”。
另外,我对jbid和ckid之间的比较感到困惑。什么是jbsiz?
for jbid in `cat tmpcsv`; do #1st Loop
for bsid in `cat bkid`; do #2nd Loop
ckid=`echo $bsid | cut -d "," -f1`
jbsiz=`echo $bsid | cut -d "," -f2`
if [ "$jbid" -eq "$ckid" ]; then
printf "There's a match at $ckid\n"
break
else
printf "No Match Found at $ckid\n"
fi
done
printf "Check for ID $jbid done\n"
sleep 2
done
答案 1 :(得分:1)
if [ "$jbid" -eq "$ckid" ]; then
printf "There's a match at $ckid\n"
break
这应该使第二个for循环结束匹配。
答案 2 :(得分:0)
if [ "$jbid" -eq "$ckid" ]; then
printf "There's a match at $ckid\n"
break
else
printf "No Match Found at $ckid\n"
fi
在then - else
之间添加中断;像上面的代码一样。