【问题标题】:How to exit a bash loop using ls?如何使用 ls 退出 bash 循环?
【发布时间】:2011-01-31 21:40:33
【问题描述】:

我想批量循环一个目录中的一系列文件,然后目录为空时退出。

在 $work 'myprog' 实际上是一个程序,它在 Maildir 中以 100 个批次处理(和存档)传入的电子邮件。

我追求一些可以放入 cron 的简单东西。

#!/bin/bash

# Setup
mkdir -p foo && touch foo/file_{1,2,3,4}.txt
alias myprog='f=`ls foo/file_*.txt | head -n1`; rm -v $f'

# Loop and then exit ?!
# This line to go into cron.
while (ls foo); do ls foo/ | wc -l; myprog; sleep 1; done

有什么想法吗?

【问题讨论】:

  • 你可以在大括号扩展中做范围:{1..4}
  • 甚至更好的是,您可以便携并使用适当的通配符file_[1234]。 :)

标签: bash loops while-loop exit


【解决方案1】:

我想你可以这样做:

#!/bin/bash
# ...
while (ls foo/* &> /dev/null); do myprog; sleep 1; done

如果没有匹配 foo/* (如果目录 foo 中没有可见文件),ls 将失败。 &> /dev/null 保持ls 安静。

【讨论】:

  • 这很快! ls foo 会返回 true 但 ls foo/* 会失败,这对我来说似乎很奇怪——但现在我知道了!我添加了一个`ls foo/ | wc -l;` 在 while 循环中观察项目减少。
  • while 语句中不需要子shell。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-10
  • 2013-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多