Thursday, June 18, 2009

Use of bash until loop - shell script


Requirement:

- I had to execute a script "my.sh" 10 times.
- my.sh basically outputs loglines that to be redirected to log file.
- Once that log file reaches 5MB, kill my.sh and again execute my.sh (continue this for 10 times)

The script:


#!/bin/sh

for((i=1;i<=10;i+=1))
do
lfile=mylog.$i
sh my.sh >> $lfile &
Pid=$!

sleep 2
until [ $(ls -l $lfile | awk '{print $5}') -gt 5000 ]
do
echo "Sleeping for next 5 seconds"
sleep 5
done

echo "Executed $i times"
kill $Pid
done


Important use:
- Bash until loop

5 comments:

Nathan said...

I like it!!
too bad im too busy these days to post some scripts here , will have some spare time in about few weeks...

Unknown said...

@Nathan, thanks. Your comments/scripts are always useful, thanks.

Mahesh Kharvi said...

i++ can also be used in place of i+1 in for loop.

Mahesh Kharvi said...

Just wonder whether you mean 5MB or 5KB, 5000 will be 5KB.

We can make use of seq command too ;)

for i in $(seq 10); do

Unknown said...

@Mahesh,thanks for the 5MB thing, I just put that, :-)

And for the seq, the problem with seq is that it has to pre evaluate seq and then it will start iterate. Anyway for smaller iterations, its fine and quite useful. Thanks.

© Jadu Saikia www.UNIXCL.com