开发者

Linux: watch number of files in directory

开发者 https://www.devze.com 2023-01-21 07:59 出处:网络
I am trying to write a shell script that waits until the number of files in a specified directory ( say ~/fit/) has reached a predefined number. What I\'ve got so far 开发者_JS百科is:

I am trying to write a shell script that waits until the number of files in a specified directory ( say ~/fit/) has reached a predefined number. What I've got so far 开发者_JS百科is:

limit = 10
while [ls ~/fit/ | wc -l -lt $limit]
do
  sleep 1
done

This says -lt is an invalid option to wc. I also tried

[$limit -gt ls ~/fit/ | wc -l]

but it didn't work either. Any help is greatly appreciated.


Try:

limit=10
while [ `ls ~/fit/ | wc -l` -lt $limit ];
...


You need:

limit=10
while [ `ls ~/fit/ | wc -l` -lt $limit ]
do
  sleep 1
done

Changes:

  • There should not be spaces around = in limit=10
  • There should be spaces surrounding [ and ]
  • You need to place the command that gets you the file count (ls ~/fit/ | wc -l) in back ticks.


A solution that minimize the use of external processes, like ls, wc and true, and manage correctly the (unusual) case of filenames containing newlines:

#!/bin/sh

nmax=10

while :; do
  n=0
  for f in ~/fit/*; do
    n=$((n+1))
  done
  [ $n -ge $nmax ] && break
  sleep 1
done

echo "Limit reached!"


Try this

while(true)
do
var=`ls -l ~/fit/ | wc -l`
  if [ $var -lt 10]
  then
    sleep 1
  else
    break
  fi
done

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号