【问题标题】:foreach random no matchforeach 随机不匹配
【发布时间】:2015-07-23 00:54:51
【问题描述】:

这是代码:

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

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

【问题讨论】:

    标签: foreach csh


    【解决方案1】:

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

    防止这种行为的最简单方法是将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
    

    【讨论】:

      猜你喜欢
      • 2018-12-17
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 2013-05-04
      • 2018-05-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多