在内循环外部保留字符串[重复]

问题描述 投票:0回答:1

我尝试使用两个循环来检查

$new
字符串是否已存在于存在列表中。但是,
$p
字符串似乎并没有在内循环之外持续存在以强制外循环中断。

#!/bin/sh

#p=0 # The $p string declaration needed to be within the inner loop (below)

while read new; do
   while read exist; do
      p=0 # The $p string declaration needed to be here--resolving the issue
      echo "$new - $exist"

      if [ "$new" = "$exist" ]; then
         #echo "$new - $exist"
         p=1
         break
      fi

   echo "$p" # Test $p string inside the inner loop

   done<existlist

   echo "$p" # Test $p string outside the inner loop

   if [ $p -ne 1 ]; then
      echo "$p"
      break
   fi
done<newlist

echo "#$new#"

这可能是一个范围问题,但我不确定。

虽然 grep 可以满足与文件相关的实现,但它不一定满足非基于文件的情况。我希望这段代码在这两种情况下都能工作。

loops shell scope sh
1个回答
0
投票

为什么不使用 grep 呢?

#!/bin/sh
while read MYSTR; do
   grep "$MYSTR" existlist
   if [ $? -eq 0 ]; then
     echo "$MYSTR exist in newlist"
     break
   fi
done<newlist
© www.soinside.com 2019 - 2024. All rights reserved.