I have a for loop that will cycle through all the files in a directory. I want to run a process on each file (in this example echo file name and sleep 5). However I want to be able to run this 5 files at a time (in the background with &). The problem is I can't figure out how to iterate $f within the while loop so that I don't end up processing the same file five times instead of five different files at the same time.
#!/bin/bash
maxjobs=5
for f in `ls /home/user/`
do
jobsrunning=0
while [ $jobsrunning -lt $maxjobs ]
do
echo "Converting file"$f
sleep 5 & #wait for 5 seconds
jobsrunning=$((jobsrunning + 1))
echo $jobsrunning
done
wait
done
jobsrunningto 0. But a much better solution exists to "feed" files to a process. Search here forfind print0 xargs. Unfortuantely the final term might bemultiple, jobs, -nor a few others.lsls ...subshell with for. "for f in /home/user/*" suffices - difference with ls is that names will be fully qualified, therefore not a drop-in replacement. May be preferable in your case because actions on those files needed to know the implied "/home/user" location as your current solution requires