while循环测试bash中是否存在具有给定模式的文件

时间:2015-08-24 11:06:22

标签: linux bash shell

如果存在给定模式的文件,我想检查这样的文件循环:

while [ ! -f "/tmp/?????-Stock.txt" ]
do
  sleep 2
done

如果存在更多像12aaa-Stock.txt,34aaa-Stock.txt这样的文件,我会收到二进制运算符预期的消息错误。

2 个答案:

答案 0 :(得分:2)

您可以使用for循环解决此问题,例如。

<?xml version="1.0" encoding="iso-8859-1"?>
<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
 <soap:Header>       
  <wsse:Security xmlns:wsse="http://schemas.xmlsoap.org/ws/2003/06/secext">
   <wsse:UsernameToken wsu:Id="sample" 
       xmlns:wsu="http://schemas.xmlsoap.org/ws/2003/06/utility">
    <wsse:Username>sample</wsse:Username>
    <wsse:Password Type="wsse:PasswordText">oracle</wsse:Password>
    <wsu:Created>2004-05-19T08:44:51Z</wsu:Created>
   </wsse:UsernameToken>
  </wsse:Security>
  <wsse:Security soap:actor="oracle" 
      xmlns:wsse="http://schemas.xmlsoap.org/ws/2003/06/secext">
   <wsse:UsernameToken wsu:Id="oracle" 
       xmlns:wsu="http://schemas.xmlsoap.org/ws/2003/06/utility">
    <wsse:Username>oracle</wsse:Username>
    <wsse:Password Type="wsse:PasswordText">oracle</wsse:Password>
    <wsu:Created>2004-05-19T08:46:04Z</wsu:Created>
   </wsse:UsernameToken>
  </wsse:Security>
 </soap:Header>
  <soap:Body>
   <getHello xmlns="http://www.oracle.com"/>
  </soap:Body>
</soap:Envelope> 

只要找不到文件,for循环就有一个要处理的项目(不匹配的模式)。如果找到多个文件,则for循环会在第一次匹配时立即退出。

@chepner注意到我可以使用DONE=no while [ "$DONE" = no ] do for name in /tmp/?????-Stock.txt do if [ -f "$name" ] then DONE=yes break fi done [ "$DONE" = no ] && sleep 2 done (旧习惯很难)。这看起来像这样:

break 2

答案 1 :(得分:2)

您可以先使用数组来获取扩展的globs,然后检查元素数量:

public static Dictionary<TKey, TValue> CloneDictionaryCloningValues<TKey, TValue>
    (Dictionary<TKey, TValue> original) where TValue : ICloneable
 {
     Dictionary<TKey, TValue> ret = new Dictionary<TKey, TValue>(original.Count,
                                                        original.Comparer);
     foreach (KeyValuePair<TKey, TValue> entry in original)
     {
         ret.Add(entry.Key, (TValue) entry.Value.Clone());
     }
     return ret;
}
当给定的glob模式没有匹配的文件时,需要

shopt -s nullglob while arr=(/tmp/?????-Stock.txt); [[ ${#arr[@]} -eq 0 ]]; do sleep 2 done 来抑制glob模式。