foreach 随机不匹配

foreach random no match

这是代码:

set source_failed = `cat mine.log`

set dest_failed = `cat their.log`

foreach t ($source_failed)
  set isdiff = 0
  set sflag = 0
  foreach t2 ($dest_failed)
    if ($t2 == $t) then
      set sflag = 1
      break
    endif
  end
  ...
end

问题是内部 foreach 循环在前几次 10 次迭代中运行正常。在那次迭代之后,突然我得到了

foreach: no match

此外,我正在遍历字符串数组,而不是文件。这个错误背后的原因是什么?

问题(可能)是 mine.log and/or their.log 包含特殊的通配符,例如 *?。 shell 将尝试将其扩展为文件。此意外模式没有匹配项,因此出现错误 "no match".

防止此行为的最简单方法是将 set noglob 添加到顶部。来自 tcsh(1):

    noglob  If set, Filename substitution and Directory stack  substitution
           (q.v.)  are  inhibited.   This  is most useful in shell scripts
           which do not deal with filenames, or after a list of  filenames
           has been obtained and further expansions are not desirable.

您可以使用 set glob.

重新启用此行为

或者,您可以使用 :q。来自 tcsh(1):

Unless  enclosed in `"' or given the `:q' modifier the results of variable
substitution may eventually be command and  filename  substituted.

[..]

When the `:q' modifier is applied to a substitution the variable will expand
to multiple words with  each  word  sepa rated  by  a blank and quoted to
prevent later command or filename sub stitution.

但是你在使用变量的时候需要非常小心引用。在下面的示例中,如果不添加引号 (set noglob is much easier),echo 命令将失败:

set source_failed = `cat source`

foreach t ($source_failed:q)
    echo "$t"
end