views:

69

answers:

4

Hi, 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 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.

+2  A: 

Try:

limit=10
while [ `ls ~/fit/ | wc -l` -lt $limit ];
...
Mic
Explanation for the OP: you had two problems. One, you need spaces by the brackets. Two, you need to tell bash that you want it to use command substitution (replace a command with the results of the command); it was simply trying to use all those things as strings. (Side note: you might want to be in the habit of using `$(...)` instead of `\`...\``, since it can be nested.)
Jefromi
+1  A: 

Try this

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

Manoj R
+2  A: 

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.
codaddict
+1  A: 

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!"
enzotib