# [Shell]How to loop?



## Ricky (Jul 13, 2012)

Hi, I have a little shell script that I would like to be running every 30 seconds. I added in the final line:

```
sleep 30
/etc/mything
```

But after start the script
[CMD=""]/etc/mything[/CMD] 
I can't do anything else, unless I break it.

Is there anything I can do?

Thank you.


----------



## UNIXgod (Jul 13, 2012)

Look at cron(8) and crontab(1) and set it to 30 second intervals. To loop based on logical construct the shell can use for and while loops respectively.


----------



## tay9000 (Jul 14, 2012)

Do you want this script to only run when you manually execute it? If so, just use the first script I wrote. Do you want this to run all day, every day every 30 seconds forever? If so, I'd use the second script and put it on a crontab to run every minute. This way the script will run, then loop once, and then be launched again at the next minute with cron. You'd want to do this for a script you want to run forever so that cron can turn it on for you if it turns off for some reason.

By the way, /etc/ is for system configuration files and system scripts (Directory Structure). You might want to put your script somewhere else to keep your customized stuff separated.

Run /etc/mything every 30 seconds forever (only good for manually executing really)

```
#!/usr/local/bin/bash
while :; do
sh /etc/mything
sleep 30
done
```

Run /etc/mything every 30 seconds two times. Put on a crontab to launch every minute. Also added logic to end the script after the second loop. It doesn't need to run after that since cron will relaunch it at the next minute.

```
#!/usr/local/bin/bash
Counter=0
while [ $Counter -lt 2 ]
do
sh /etc/mything
Counter=$(expr $Counter + 1)
if [ $Counter -ge 2 ]
then exit
fi
sleep 30
done
```


----------



## fluca1978 (Jul 16, 2012)

Ricky said:
			
		

> But after start the script
> [CMD=""]/etc/mything[/CMD]
> I can't do anything else, unless I break it.
> 
> Is there anything I can do?



In interactive mode the shell will wait for the child process to exit, and therefore you will not be able to run any other command. If you need to run this script and do something else in the meantime, then you have to send it to backgroun (not interactive):

[CMD=""]/etc/mything &[/CMD] 

and this will keep the process running until it either exits or the parent process (your shell) is closed. If you need to run the command even when logged out, use nohup(1):

```
nohup /etc/mything &
```

Apart this basic shell concepts, as already pointed out, the best thing to do are:

do not place the script into /etc
use cron, at, periodic or stuff like that for regular scheduling
do a loop using a for/while construct


----------

