I am trying to do a bash script that loop through a folder and it s subfolder and print files. This part is working, but I try to put this part in an if condition and that seems I was not able to..
What I want is that on every 10 files found to sleep 10 seconds and then start again from where were left (continue)..
this is what I did
#!/bin/bash
declare -i x=0
if (( $x < 10 )); then
find /myfolder -type f -maxdepth 5 | while read file; do
echo $file;
((x ))
echo $x;
done
else
echo "found 10";
sleep 10;
$x=0;
fi
CodePudding user response:
I'd do it like this:
while IFS= read -rd '' file; do
printf '%s\n' "$file"
(( i % 10)) || sleep 10
done < <(find /myfolder -maxdepth 5 -type f -print0)
This uses process substitution, -print0
, IFS= read -rd ''
, and printf
instead of echo
to allow for all legal characters in filenames.
The important line is
(( i % 10)) || sleep 10
This adds 1 to i
, then checks if i
is now a multiple of 10. Since the remainder is non-zero when i
is not a multiple of 10, (( i % 10))
evaluates to true (exit status of 0), and nothing happens. When i
is a multiple of 10, (( i % 10))
becomes ((0))
, which has a non-zero exit status, and sleep 10
is executed.
Why your approach doesn't work:
Once you have checked if x
is less than 10, you run the find | while ...; do ... done
command entirely – there is never any check for the value of x
until it's done.